BlueGit

timfa bluegit

Merge branch 'stage' into master

timfa Grok Bot · pushed by timfa

Authored 2026-11-13 · 4 days ago

Hash
87ddf7ead12124148f1b3fdb2a223b3700755fb8
Pipeline
Passed
34 files changed +1189 −51
README.md +2 −2
@@ -14,7 +14,7 @@ Het logo is de blauwe ster: [`assets/logo.svg`](assets/logo.svg).
14 14 - Op de project-overzichtspagina staat een commitgrafiek rechts van de centrale kolom, als er plek is. De centrale kolom schuift daardoor iets naar links; op brede schermen vult de grafiek alle ruimte rechts van de kolom tot aan de rand. Elke commit staat op één regel; de lijnen lopen in verticale lanes met afgeronde 90-graden bochten, en de avatar is de commitknoop. De tekst begint in één kolom, rechts van de meest rechtse lane. Elke avatar staat in de SVG op de lane van die commit (niet via inline CSS: de CSP staat geen style-attributen toe). De grafiek wordt niet verkleind en heeft geen eigen scrollbar; als hij onderaan het scherm stopt, vagen de lijnen naar transparant weg. Te lange committekst vervaagt naar transparant (geen ellipsis) en toont bij hover het volledige bericht via een native title. Past de volle grafiek (met tekstkolom) niet, dan verschijnt een smalle modus: dezelfde lanes, avatars en labels, maar zonder committekst; hover op een commit toont het bericht via de native SVG-title. In die modus valt van een branchnaam alles t/m de laatste '/' weg (de volledige naam blijft in title). Elke commitknoop heeft een dunne omlijning in de lanekleur; de gekozen branch houdt een dikkere gloed. Alleen als ook de smalle modus niet past, zoals op mobiel, blijft de grafiek verborgen. Wordt de centrale kolom te smal (sidebar plus smalle grafiek, rond 1024–1280px), dan schuift Project information onder de inhoud; de laatste-commit-balk wrapt, de branchrij blijft op één regel en de bestandstabel toont alle drie de kolommen met ellipsis. Op een brede kolom (zoals 1920px) blijft de twee-koloms lay-out. De lijn van de in de dropdown gekozen branch gloeit. De hoofdbranch gebruikt de BlueGit-blauw; andere branches krijgen een vaste kleur uit hun naam. De grafiek wordt in het geheugen bewaard (LRU) en bij een push ververst, zodat herhaald laden geen git-I/O op schijf doet.
15 15 - Merge requests met reviews, squash en het verwijderen van de bronbranch na een merge.
16 16 - Issues, met beschrijvingssjablonen in `.bluegit/issue_templates`. Merge requests gebruiken `.bluegit/merge_request_templates`. `Default.md` vult een lege beschrijving. Dezelfde namen onder `.gitlab/` zijn een terugval.
17 - Een ingebouwde CI-runner, Steve. Het bestand is `blue-ci-cd.yml`. Elke job draait in een eigen container. `image: bluegit/base` en de andere aliassen zijn image-presets die Steve lokaal bouwt.
17 - Een ingebouwde CI-runner, Steve. Het bestand is `blue-ci-cd.yml`. Elke job draait in een eigen container. `image: bluegit/base` en de andere aliassen zijn image-presets die Steve lokaal bouwt. CI kan per project worden gepauzeerd (instellingen of `ci_paused` op `PUT /api/v1/projects/{owner}/{repo}`): er worden dan geen nieuwe pipelines in de wachtrij gezet; jobs die al lopen of wachten, lopen wel af.
18 18 - Jobs die je niet halverwege wilt stoppen (FTP-upload, databasemigratie) markeer je met `doNotInterrupt: true`: BlueGit stopt ze nooit automatisch, een nieuwere pipeline op dezelfde ref wacht erop, en handmatig stoppen vraagt om bevestiging. Zie [docs/CI.md](docs/CI.md#donotinterrupt).
19 19 - Webhooks op een repository of een groep, met presets, een eigen body en een overzicht van de laatste afleveringen.
20 20 - Geheimen als omgevingsvariabelen in een job. Een beschermd geheim gaat alleen mee op een beschermde branch of een tag die op een beschermd tagpatroon past.
@@ -51,7 +51,7 @@ Details en de OIDC-controles staan in [docs/AUTH.md](docs/AUTH.md). Kort, stap v
51 51 2. Kies één tenant (*Accounts in this organizational directory only* / single tenant).
52 52 3. Platform: **Web**. De redirect-URI moet exact `{base_url}{auth.redirect_path}` zijn, het pad dat BlueGit verwacht. `auth.redirect_path` is standaard `/auth/callback`, dus bijvoorbeeld `https://git.timfalken.com/auth/callback`. Een ander pad, schema (`http` vs `https`) of een slash te veel of te weinig geeft een redirect-mismatch.
53 53 4. Maak onder *Certificates & secrets* een client secret aan. Noteer de waarde (die is maar één keer zichtbaar) en de verloopdatum; na verlopen stopt aanmelden.
54 5. BlueGit vraagt de scopes `openid`, `profile` en `email`. Die horen bij OpenID Connect; er zijn geen extra Graph-rechten nodig voor aanmelden.
54 5. BlueGit vraagt de scopes `openid`, `profile`, `email` en `User.Read`. De eerste drie horen bij OpenID Connect. `User.Read` is nodig om bij het aanmelden de profielfoto op te halen bij Microsoft Graph (`GET https://graph.microsoft.com/v1.0/me/photo/$value`). Voeg *Microsoft Graph → User.Read* (gedelegeerd) toe onder API-machtigingen van de app-registratie en geef desnoods admin-toestemming. Zonder foto (404) toont BlueGit initialen; een handmatig geüploade avatar wordt niet overschreven.
55 55 6. Op het overzicht van de app-registratie staan de **Directory (tenant) ID** (`auth.tenant_id`) en de **Application (client) ID** (`auth.client_id`).
56 56
57 57 Zet in `/etc/bluegit/config.yml` (geen echte geheimen in dit bestand of in deze docs):
@@ -14,7 +14,7 @@ Het logo is de blauwe ster: [`assets/logo.svg`](assets/logo.svg).
14- Op de project-overzichtspagina staat een commitgrafiek rechts van de centrale kolom, als er plek is. De centrale kolom schuift daardoor iets naar links; op brede schermen vult de grafiek alle ruimte rechts van de kolom tot aan de rand. Elke commit staat op één regel; de lijnen lopen in verticale lanes met afgeronde 90-graden bochten, en de avatar is de commitknoop. De tekst begint in één kolom, rechts van de meest rechtse lane. Elke avatar staat in de SVG op de lane van die commit (niet via inline CSS: de CSP staat geen style-attributen toe). De grafiek wordt niet verkleind en heeft geen eigen scrollbar; als hij onderaan het scherm stopt, vagen de lijnen naar transparant weg. Te lange committekst vervaagt naar transparant (geen ellipsis) en toont bij hover het volledige bericht via een native title. Past de volle grafiek (met tekstkolom) niet, dan verschijnt een smalle modus: dezelfde lanes, avatars en labels, maar zonder committekst; hover op een commit toont het bericht via de native SVG-title. In die modus valt van een branchnaam alles t/m de laatste '/' weg (de volledige naam blijft in title). Elke commitknoop heeft een dunne omlijning in de lanekleur; de gekozen branch houdt een dikkere gloed. Alleen als ook de smalle modus niet past, zoals op mobiel, blijft de grafiek verborgen. Wordt de centrale kolom te smal (sidebar plus smalle grafiek, rond 1024–1280px), dan schuift Project information onder de inhoud; de laatste-commit-balk wrapt, de branchrij blijft op één regel en de bestandstabel toont alle drie de kolommen met ellipsis. Op een brede kolom (zoals 1920px) blijft de twee-koloms lay-out. De lijn van de in de dropdown gekozen branch gloeit. De hoofdbranch gebruikt de BlueGit-blauw; andere branches krijgen een vaste kleur uit hun naam. De grafiek wordt in het geheugen bewaard (LRU) en bij een push ververst, zodat herhaald laden geen git-I/O op schijf doet.
14- Op de project-overzichtspagina staat een commitgrafiek rechts van de centrale kolom, als er plek is. De centrale kolom schuift daardoor iets naar links; op brede schermen vult de grafiek alle ruimte rechts van de kolom tot aan de rand. Elke commit staat op één regel; de lijnen lopen in verticale lanes met afgeronde 90-graden bochten, en de avatar is de commitknoop. De tekst begint in één kolom, rechts van de meest rechtse lane. Elke avatar staat in de SVG op de lane van die commit (niet via inline CSS: de CSP staat geen style-attributen toe). De grafiek wordt niet verkleind en heeft geen eigen scrollbar; als hij onderaan het scherm stopt, vagen de lijnen naar transparant weg. Te lange committekst vervaagt naar transparant (geen ellipsis) en toont bij hover het volledige bericht via een native title. Past de volle grafiek (met tekstkolom) niet, dan verschijnt een smalle modus: dezelfde lanes, avatars en labels, maar zonder committekst; hover op een commit toont het bericht via de native SVG-title. In die modus valt van een branchnaam alles t/m de laatste '/' weg (de volledige naam blijft in title). Elke commitknoop heeft een dunne omlijning in de lanekleur; de gekozen branch houdt een dikkere gloed. Alleen als ook de smalle modus niet past, zoals op mobiel, blijft de grafiek verborgen. Wordt de centrale kolom te smal (sidebar plus smalle grafiek, rond 1024–1280px), dan schuift Project information onder de inhoud; de laatste-commit-balk wrapt, de branchrij blijft op één regel en de bestandstabel toont alle drie de kolommen met ellipsis. Op een brede kolom (zoals 1920px) blijft de twee-koloms lay-out. De lijn van de in de dropdown gekozen branch gloeit. De hoofdbranch gebruikt de BlueGit-blauw; andere branches krijgen een vaste kleur uit hun naam. De grafiek wordt in het geheugen bewaard (LRU) en bij een push ververst, zodat herhaald laden geen git-I/O op schijf doet.
15- Merge requests met reviews, squash en het verwijderen van de bronbranch na een merge.
15- Merge requests met reviews, squash en het verwijderen van de bronbranch na een merge.
16- Issues, met beschrijvingssjablonen in `.bluegit/issue_templates`. Merge requests gebruiken `.bluegit/merge_request_templates`. `Default.md` vult een lege beschrijving. Dezelfde namen onder `.gitlab/` zijn een terugval.
16- Issues, met beschrijvingssjablonen in `.bluegit/issue_templates`. Merge requests gebruiken `.bluegit/merge_request_templates`. `Default.md` vult een lege beschrijving. Dezelfde namen onder `.gitlab/` zijn een terugval.
17- Een ingebouwde CI-runner, Steve. Het bestand is `blue-ci-cd.yml`. Elke job draait in een eigen container. `image: bluegit/base` en de andere aliassen zijn image-presets die Steve lokaal bouwt.
17- Een ingebouwde CI-runner, Steve. Het bestand is `blue-ci-cd.yml`. Elke job draait in een eigen container. `image: bluegit/base` en de andere aliassen zijn image-presets die Steve lokaal bouwt. CI kan per project worden gepauzeerd (instellingen of `ci_paused` op `PUT /api/v1/projects/{owner}/{repo}`): er worden dan geen nieuwe pipelines in de wachtrij gezet; jobs die al lopen of wachten, lopen wel af.
18- Jobs die je niet halverwege wilt stoppen (FTP-upload, databasemigratie) markeer je met `doNotInterrupt: true`: BlueGit stopt ze nooit automatisch, een nieuwere pipeline op dezelfde ref wacht erop, en handmatig stoppen vraagt om bevestiging. Zie [docs/CI.md](docs/CI.md#donotinterrupt).
18- Jobs die je niet halverwege wilt stoppen (FTP-upload, databasemigratie) markeer je met `doNotInterrupt: true`: BlueGit stopt ze nooit automatisch, een nieuwere pipeline op dezelfde ref wacht erop, en handmatig stoppen vraagt om bevestiging. Zie [docs/CI.md](docs/CI.md#donotinterrupt).
19- Webhooks op een repository of een groep, met presets, een eigen body en een overzicht van de laatste afleveringen.
19- Webhooks op een repository of een groep, met presets, een eigen body en een overzicht van de laatste afleveringen.
20- Geheimen als omgevingsvariabelen in een job. Een beschermd geheim gaat alleen mee op een beschermde branch of een tag die op een beschermd tagpatroon past.
20- Geheimen als omgevingsvariabelen in een job. Een beschermd geheim gaat alleen mee op een beschermde branch of een tag die op een beschermd tagpatroon past.
@@ -51,7 +51,7 @@ Details en de OIDC-controles staan in [docs/AUTH.md](docs/AUTH.md). Kort, stap v
512. Kies één tenant (*Accounts in this organizational directory only* / single tenant).
512. Kies één tenant (*Accounts in this organizational directory only* / single tenant).
523. Platform: **Web**. De redirect-URI moet exact `{base_url}{auth.redirect_path}` zijn, het pad dat BlueGit verwacht. `auth.redirect_path` is standaard `/auth/callback`, dus bijvoorbeeld `https://git.timfalken.com/auth/callback`. Een ander pad, schema (`http` vs `https`) of een slash te veel of te weinig geeft een redirect-mismatch.
523. Platform: **Web**. De redirect-URI moet exact `{base_url}{auth.redirect_path}` zijn, het pad dat BlueGit verwacht. `auth.redirect_path` is standaard `/auth/callback`, dus bijvoorbeeld `https://git.timfalken.com/auth/callback`. Een ander pad, schema (`http` vs `https`) of een slash te veel of te weinig geeft een redirect-mismatch.
534. Maak onder *Certificates & secrets* een client secret aan. Noteer de waarde (die is maar één keer zichtbaar) en de verloopdatum; na verlopen stopt aanmelden.
534. Maak onder *Certificates & secrets* een client secret aan. Noteer de waarde (die is maar één keer zichtbaar) en de verloopdatum; na verlopen stopt aanmelden.
545. BlueGit vraagt de scopes `openid`, `profile` en `email`. Die horen bij OpenID Connect; er zijn geen extra Graph-rechten nodig voor aanmelden.
545. BlueGit vraagt de scopes `openid`, `profile`, `email` en `User.Read`. De eerste drie horen bij OpenID Connect. `User.Read` is nodig om bij het aanmelden de profielfoto op te halen bij Microsoft Graph (`GET https://graph.microsoft.com/v1.0/me/photo/$value`). Voeg *Microsoft Graph → User.Read* (gedelegeerd) toe onder API-machtigingen van de app-registratie en geef desnoods admin-toestemming. Zonder foto (404) toont BlueGit initialen; een handmatig geüploade avatar wordt niet overschreven.
556. Op het overzicht van de app-registratie staan de **Directory (tenant) ID** (`auth.tenant_id`) en de **Application (client) ID** (`auth.client_id`).
556. Op het overzicht van de app-registratie staan de **Directory (tenant) ID** (`auth.tenant_id`) en de **Application (client) ID** (`auth.client_id`).
56
56
57Zet in `/etc/bluegit/config.yml` (geen echte geheimen in dit bestand of in deze docs):
57Zet in `/etc/bluegit/config.yml` (geen echte geheimen in dit bestand of in deze docs):
cmd/bluegit-runner/main.go +3 −1
@@ -238,8 +238,10 @@ func (c *client) status() runnercfg.Status {
238 238 if name == "" {
239 239 name = c.cfg.Name
240 240 }
241 docker := runnercfg.PingDocker(context.Background(), c.cfg.Docker)
242 online := !c.seen.IsZero() && time.Since(c.seen) < 90*time.Second && docker.Reachable
241 243 return runnercfg.Status{Kind: "standalone", Name: name, Version: version, ServerURL: c.cfg.URL,
242 Online: !c.seen.IsZero() && time.Since(c.seen) < 90*time.Second, LastContact: c.seen, ServerPause: c.srvPause}
244 Online: online, LastContact: c.seen, ServerPause: c.srvPause, Docker: docker}
243 245 }
244 246
245 247 // heartbeat meldt pauze en (lokaal ingestelde) naam aan de server.
@@ -238,8 +238,10 @@ func (c *client) status() runnercfg.Status {
238 if name == "" {
238 if name == "" {
239 name = c.cfg.Name
239 name = c.cfg.Name
240 }
240 }
241 docker := runnercfg.PingDocker(context.Background(), c.cfg.Docker)
242 online := !c.seen.IsZero() && time.Since(c.seen) < 90*time.Second && docker.Reachable
241 return runnercfg.Status{Kind: "standalone", Name: name, Version: version, ServerURL: c.cfg.URL,
243 return runnercfg.Status{Kind: "standalone", Name: name, Version: version, ServerURL: c.cfg.URL,
242 Online: !c.seen.IsZero() && time.Since(c.seen) < 90*time.Second, LastContact: c.seen, ServerPause: c.srvPause}
244 Online: online, LastContact: c.seen, ServerPause: c.srvPause, Docker: docker}
243}
245}
244
246
245// heartbeat meldt pauze en (lokaal ingestelde) naam aan de server.
247// heartbeat meldt pauze en (lokaal ingestelde) naam aan de server.
docs/AUTH.md +4 −2
@@ -45,7 +45,7 @@ Een leeg `client_secret` valt terug op het bestand, en dat weer op `BLUEGIT_AUTH
45 45
46 46 ## Microsoft Entra ID (`mode: entra`)
47 47
48 Entra is wél OpenID Connect. BlueGit gebruikt de authorization-code-flow met `scope=openid profile email` en PKCE S256. De login zet HttpOnly-cookies (`bluegit_oauth_state`, `bluegit_oauth_nonce`, `bluegit_oauth_pkce`; 600 seconden, `Secure` bij HTTPS, `SameSite=Lax`) en wist ze na de callback. In het ID-token controleert BlueGit: `nonce`, handtekening (JWKS, alleen RS256; `none` en HS256 worden geweigerd), `iss`, `aud`, verplichte `exp` (met 60 seconden klokverschuiving; ook `nbf` en `iat` als ze er zijn), en verplichte `tid` die case-insensitive gelijk moet zijn aan `auth.tenant_id`. `authorization_endpoint`, `token_endpoint` en `jwks_uri` moeten op dezelfde host staan als de issuer; bij een HTTPS-issuer moeten die eindpunten ook HTTPS zijn. Een zelfgezette `auth.issuer` moet HTTPS zijn, behalve op localhost (voor tests). Alleen één tenant: zet `tenant_id` op de Directory (tenant) ID van die directory.
48 Entra is wél OpenID Connect. BlueGit gebruikt de authorization-code-flow met `scope=openid profile email User.Read` en PKCE S256. De login zet HttpOnly-cookies (`bluegit_oauth_state`, `bluegit_oauth_nonce`, `bluegit_oauth_pkce`; 600 seconden, `Secure` bij HTTPS, `SameSite=Lax`) en wist ze na de callback. In het ID-token controleert BlueGit: `nonce`, handtekening (JWKS, alleen RS256; `none` en HS256 worden geweigerd), `iss`, `aud`, verplichte `exp` (met 60 seconden klokverschuiving; ook `nbf` en `iat` als ze er zijn), en verplichte `tid` die case-insensitive gelijk moet zijn aan `auth.tenant_id`. `authorization_endpoint`, `token_endpoint` en `jwks_uri` moeten op dezelfde host staan als de issuer; bij een HTTPS-issuer moeten die eindpunten ook HTTPS zijn. Een zelfgezette `auth.issuer` moet HTTPS zijn, behalve op localhost (voor tests). Alleen één tenant: zet `tenant_id` op de Directory (tenant) ID van die directory.
49 49
50 50 Een korte checklist staat ook in de [README](../README.md#microsoft-entra-id).
51 51
@@ -79,13 +79,15 @@ Het clientgeheim hoort in `auth.client_secret`, in `auth.client_secret_file` (bi
79 79
80 80 De bestaande knop **Aanmelden** (navigatie, `/login`) start de Entra-flow zodra `auth.mode: entra` staat. Er is geen aparte knop.
81 81
82 Voeg onder *API-machtigingen* van de app-registratie **Microsoft Graph → User.Read** (gedelegeerd) toe en geef zo nodig admin-toestemming. Bij het aanmelden haalt BlueGit `GET https://graph.microsoft.com/v1.0/me/photo/$value` op (alleen die host, met een maximale grootte en typecontrole). Een 404 (geen foto) is geen fout: de UI gebruikt initialen. Een later opnieuw inloggen ververst de Graph-foto, maar overschrijft geen handmatig geüploade avatar.
83
82 84 ### Identiteit → BlueGit-gebruiker
83 85
84 86 | BlueGit | Bron bij Entra |
85 87 | --- | --- |
86 88 | `auth_id` (numeriek) | Stabiele hash van `tid` + `oid` (valt terug op `sub` als `oid` ontbreekt) |
87 89 | `username` | Lokaal deel van `preferred_username` of `email`, gesaneerd naar kleine letters; anders `u` + korte hash van `oid` |
88 | `avatar_url` | Leeg (initialen in de UI) |
90 | `avatar_url` | Profielfoto van Microsoft Graph, bewaard als lokale avatar; zonder foto (404) initialen in de UI. Een handmatig geüploade avatar wordt niet overschreven. |
89 91 | `auth_admin` / IdP-`is_admin` | Altijd false; Entra-rollen maken niemand BlueGit-beheerder |
90 92
91 93 Installatiebeheerder blijft: alleen de eerste aangemelde gebruiker op deze installatie.
@@ -45,7 +45,7 @@ Een leeg `client_secret` valt terug op het bestand, en dat weer op `BLUEGIT_AUTH
45
45
46## Microsoft Entra ID (`mode: entra`)
46## Microsoft Entra ID (`mode: entra`)
47
47
48Entra is wél OpenID Connect. BlueGit gebruikt de authorization-code-flow met `scope=openid profile email` en PKCE S256. De login zet HttpOnly-cookies (`bluegit_oauth_state`, `bluegit_oauth_nonce`, `bluegit_oauth_pkce`; 600 seconden, `Secure` bij HTTPS, `SameSite=Lax`) en wist ze na de callback. In het ID-token controleert BlueGit: `nonce`, handtekening (JWKS, alleen RS256; `none` en HS256 worden geweigerd), `iss`, `aud`, verplichte `exp` (met 60 seconden klokverschuiving; ook `nbf` en `iat` als ze er zijn), en verplichte `tid` die case-insensitive gelijk moet zijn aan `auth.tenant_id`. `authorization_endpoint`, `token_endpoint` en `jwks_uri` moeten op dezelfde host staan als de issuer; bij een HTTPS-issuer moeten die eindpunten ook HTTPS zijn. Een zelfgezette `auth.issuer` moet HTTPS zijn, behalve op localhost (voor tests). Alleen één tenant: zet `tenant_id` op de Directory (tenant) ID van die directory.
48Entra is wél OpenID Connect. BlueGit gebruikt de authorization-code-flow met `scope=openid profile email User.Read` en PKCE S256. De login zet HttpOnly-cookies (`bluegit_oauth_state`, `bluegit_oauth_nonce`, `bluegit_oauth_pkce`; 600 seconden, `Secure` bij HTTPS, `SameSite=Lax`) en wist ze na de callback. In het ID-token controleert BlueGit: `nonce`, handtekening (JWKS, alleen RS256; `none` en HS256 worden geweigerd), `iss`, `aud`, verplichte `exp` (met 60 seconden klokverschuiving; ook `nbf` en `iat` als ze er zijn), en verplichte `tid` die case-insensitive gelijk moet zijn aan `auth.tenant_id`. `authorization_endpoint`, `token_endpoint` en `jwks_uri` moeten op dezelfde host staan als de issuer; bij een HTTPS-issuer moeten die eindpunten ook HTTPS zijn. Een zelfgezette `auth.issuer` moet HTTPS zijn, behalve op localhost (voor tests). Alleen één tenant: zet `tenant_id` op de Directory (tenant) ID van die directory.
49
49
50Een korte checklist staat ook in de [README](../README.md#microsoft-entra-id).
50Een korte checklist staat ook in de [README](../README.md#microsoft-entra-id).
51
51
@@ -79,13 +79,15 @@ Het clientgeheim hoort in `auth.client_secret`, in `auth.client_secret_file` (bi
79
79
80De bestaande knop **Aanmelden** (navigatie, `/login`) start de Entra-flow zodra `auth.mode: entra` staat. Er is geen aparte knop.
80De bestaande knop **Aanmelden** (navigatie, `/login`) start de Entra-flow zodra `auth.mode: entra` staat. Er is geen aparte knop.
81
81
82Voeg onder *API-machtigingen* van de app-registratie **Microsoft Graph → User.Read** (gedelegeerd) toe en geef zo nodig admin-toestemming. Bij het aanmelden haalt BlueGit `GET https://graph.microsoft.com/v1.0/me/photo/$value` op (alleen die host, met een maximale grootte en typecontrole). Een 404 (geen foto) is geen fout: de UI gebruikt initialen. Een later opnieuw inloggen ververst de Graph-foto, maar overschrijft geen handmatig geüploade avatar.
83
82### Identiteit → BlueGit-gebruiker
84### Identiteit → BlueGit-gebruiker
83
85
84| BlueGit | Bron bij Entra |
86| BlueGit | Bron bij Entra |
85| --- | --- |
87| --- | --- |
86| `auth_id` (numeriek) | Stabiele hash van `tid` + `oid` (valt terug op `sub` als `oid` ontbreekt) |
88| `auth_id` (numeriek) | Stabiele hash van `tid` + `oid` (valt terug op `sub` als `oid` ontbreekt) |
87| `username` | Lokaal deel van `preferred_username` of `email`, gesaneerd naar kleine letters; anders `u` + korte hash van `oid` |
89| `username` | Lokaal deel van `preferred_username` of `email`, gesaneerd naar kleine letters; anders `u` + korte hash van `oid` |
88| `avatar_url` | Leeg (initialen in de UI) |
90| `avatar_url` | Profielfoto van Microsoft Graph, bewaard als lokale avatar; zonder foto (404) initialen in de UI. Een handmatig geüploade avatar wordt niet overschreven. |
89| `auth_admin` / IdP-`is_admin` | Altijd false; Entra-rollen maken niemand BlueGit-beheerder |
91| `auth_admin` / IdP-`is_admin` | Altijd false; Entra-rollen maken niemand BlueGit-beheerder |
90
92
91Installatiebeheerder blijft: alleen de eerste aangemelde gebruiker op deze installatie.
93Installatiebeheerder blijft: alleen de eerste aangemelde gebruiker op deze installatie.
internal/auth/entra.go +4 −2
@@ -16,7 +16,7 @@ import (
16 16 )
17 17
18 18 // entraScope is wat de authorization-code-flow bij Entra vraagt.
19 const entraScope = "openid profile email"
19 const entraScope = "openid profile email User.Read"
20 20
21 21 // idTokenSkew is de toegestane klokverschuiving bij exp, nbf en iat.
22 22 const idTokenSkew = 60 * time.Second
@@ -30,6 +30,8 @@ type Entra struct {
30 30 Secret string
31 31 UserAgent string
32 32 HTTP *http.Client
33 // GraphPhotoURL overschrijft de foto-URL van Microsoft Graph (tests).
34 GraphPhotoURL string
33 35
34 36 mu sync.Mutex
35 37 authz string
@@ -52,7 +54,7 @@ func NewEntra(issuer, tenantID, clientID, secret, userAgent string) *Entra {
52 54 }
53 55 }
54 56
55 // AuthorizeURL stuurt de browser naar Entra met openid-profile-email, nonce en PKCE S256.
57 // AuthorizeURL stuurt de browser naar Entra met openid, profile, email en User.Read, nonce en PKCE S256.
56 58 func (e *Entra) AuthorizeURL(state, nonce, redirectURI, codeChallenge string) string {
57 59 authz, err := e.authorizeEndpoint(context.Background())
58 60 if err != nil {
@@ -16,7 +16,7 @@ import (
16)
16)
17
17
18// entraScope is wat de authorization-code-flow bij Entra vraagt.
18// entraScope is wat de authorization-code-flow bij Entra vraagt.
19const entraScope = "openid profile email"
19const entraScope = "openid profile email User.Read"
20
20
21// idTokenSkew is de toegestane klokverschuiving bij exp, nbf en iat.
21// idTokenSkew is de toegestane klokverschuiving bij exp, nbf en iat.
22const idTokenSkew = 60 * time.Second
22const idTokenSkew = 60 * time.Second
@@ -30,6 +30,8 @@ type Entra struct {
30 Secret string
30 Secret string
31 UserAgent string
31 UserAgent string
32 HTTP *http.Client
32 HTTP *http.Client
33 // GraphPhotoURL overschrijft de foto-URL van Microsoft Graph (tests).
34 GraphPhotoURL string
33
35
34 mu sync.Mutex
36 mu sync.Mutex
35 authz string
37 authz string
@@ -52,7 +54,7 @@ func NewEntra(issuer, tenantID, clientID, secret, userAgent string) *Entra {
52 }
54 }
53}
55}
54
56
55// AuthorizeURL stuurt de browser naar Entra met openid-profile-email, nonce en PKCE S256.
57// AuthorizeURL stuurt de browser naar Entra met openid, profile, email en User.Read, nonce en PKCE S256.
56func (e *Entra) AuthorizeURL(state, nonce, redirectURI, codeChallenge string) string {
58func (e *Entra) AuthorizeURL(state, nonce, redirectURI, codeChallenge string) string {
57 authz, err := e.authorizeEndpoint(context.Background())
59 authz, err := e.authorizeEndpoint(context.Background())
58 if err != nil {
60 if err != nil {
internal/auth/entra_photo.go added +116 −0
@@ -0,0 +1,116 @@
1 package auth
2
3 import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "image"
9 _ "image/gif"
10 _ "image/jpeg"
11 _ "image/png"
12 "io"
13 "net/http"
14 "net/url"
15 "strings"
16 "time"
17 )
18
19 // ErrNoPhoto betekent dat Entra/Graph geen profielfoto heeft (404).
20 var ErrNoPhoto = errors.New("auth: geen Entra-profielfoto")
21
22 const (
23 defaultGraphPhotoURL = "https://graph.microsoft.com/v1.0/me/photo/$value"
24 graphPhotoMax = 2 << 20
25 )
26
27 // GraphPhotoURL overschrijft de Graph-foto-URL (alleen voor tests).
28 // Leeg is de productie-URL op graph.microsoft.com.
29 func (e *Entra) photoURL() string {
30 if e != nil && strings.TrimSpace(e.GraphPhotoURL) != "" {
31 return strings.TrimSpace(e.GraphPhotoURL)
32 }
33 return defaultGraphPhotoURL
34 }
35
36 // FetchPhoto haalt de profielfoto op bij Microsoft Graph.
37 // Alleen de Graph-host (of de testhost in GraphPhotoURL) is toegestaan.
38 // 404 wordt ErrNoPhoto; andere fouten blijven een gewone error.
39 // De bytes zijn een geldige rasterafbeelding, begrensd tot graphPhotoMax.
40 func (e *Entra) FetchPhoto(ctx context.Context, accessToken string) ([]byte, error) {
41 if e == nil || strings.TrimSpace(accessToken) == "" {
42 return nil, ErrNoPhoto
43 }
44 rawURL := e.photoURL()
45 if err := e.graphURLOK(rawURL); err != nil {
46 return nil, err
47 }
48 req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
49 if err != nil {
50 return nil, err
51 }
52 req.Header.Set("Authorization", "Bearer "+accessToken)
53 req.Header.Set("Accept", "image/*")
54 if e.UserAgent != "" {
55 req.Header.Set("User-Agent", e.UserAgent)
56 }
57 res, err := e.graphClient().Do(req)
58 if err != nil {
59 return nil, fmt.Errorf("auth: Graph-foto: %w", err)
60 }
61 defer res.Body.Close()
62 if res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusNoContent {
63 _, _ = io.Copy(io.Discard, io.LimitReader(res.Body, 64<<10))
64 return nil, ErrNoPhoto
65 }
66 data, err := io.ReadAll(io.LimitReader(res.Body, graphPhotoMax+1))
67 if err != nil {
68 return nil, fmt.Errorf("auth: Graph-foto lezen: %w", err)
69 }
70 if len(data) > graphPhotoMax {
71 return nil, fmt.Errorf("auth: Graph-foto te groot")
72 }
73 if res.StatusCode >= 400 {
74 return nil, fmt.Errorf("auth: Graph-foto: %s", res.Status)
75 }
76 if _, _, err := image.Decode(bytes.NewReader(data)); err != nil {
77 return nil, fmt.Errorf("auth: Graph-foto ongeldig: %w", err)
78 }
79 return data, nil
80 }
81
82 func (e *Entra) graphClient() *http.Client {
83 base := e.HTTP
84 if base == nil {
85 base = &http.Client{Timeout: 15 * time.Second}
86 }
87 c := *base
88 c.CheckRedirect = func(req *http.Request, via []*http.Request) error {
89 if len(via) >= 5 {
90 return fmt.Errorf("auth: te veel redirects")
91 }
92 return e.graphURLOK(req.URL.String())
93 }
94 return &c
95 }
96
97 func (e *Entra) graphURLOK(raw string) error {
98 u, err := url.Parse(raw)
99 if err != nil || u.Host == "" {
100 return fmt.Errorf("auth: ongeldige Graph-URL")
101 }
102 want, err := url.Parse(e.photoURL())
103 if err != nil || want.Host == "" {
104 return fmt.Errorf("auth: ongeldige Graph-URL")
105 }
106 if !strings.EqualFold(u.Host, want.Host) {
107 return fmt.Errorf("auth: Graph-foto alleen vanaf %s", want.Host)
108 }
109 if e.GraphPhotoURL == "" && u.Scheme != "https" {
110 return fmt.Errorf("auth: Graph-foto moet HTTPS zijn")
111 }
112 if u.Scheme != "https" && u.Scheme != "http" {
113 return fmt.Errorf("auth: ongeldige Graph-URL")
114 }
115 return nil
116 }
@@ -0,0 +1,116 @@
1package auth
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "image"
9 _ "image/gif"
10 _ "image/jpeg"
11 _ "image/png"
12 "io"
13 "net/http"
14 "net/url"
15 "strings"
16 "time"
17)
18
19// ErrNoPhoto betekent dat Entra/Graph geen profielfoto heeft (404).
20var ErrNoPhoto = errors.New("auth: geen Entra-profielfoto")
21
22const (
23 defaultGraphPhotoURL = "https://graph.microsoft.com/v1.0/me/photo/$value"
24 graphPhotoMax = 2 << 20
25)
26
27// GraphPhotoURL overschrijft de Graph-foto-URL (alleen voor tests).
28// Leeg is de productie-URL op graph.microsoft.com.
29func (e *Entra) photoURL() string {
30 if e != nil && strings.TrimSpace(e.GraphPhotoURL) != "" {
31 return strings.TrimSpace(e.GraphPhotoURL)
32 }
33 return defaultGraphPhotoURL
34}
35
36// FetchPhoto haalt de profielfoto op bij Microsoft Graph.
37// Alleen de Graph-host (of de testhost in GraphPhotoURL) is toegestaan.
38// 404 wordt ErrNoPhoto; andere fouten blijven een gewone error.
39// De bytes zijn een geldige rasterafbeelding, begrensd tot graphPhotoMax.
40func (e *Entra) FetchPhoto(ctx context.Context, accessToken string) ([]byte, error) {
41 if e == nil || strings.TrimSpace(accessToken) == "" {
42 return nil, ErrNoPhoto
43 }
44 rawURL := e.photoURL()
45 if err := e.graphURLOK(rawURL); err != nil {
46 return nil, err
47 }
48 req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
49 if err != nil {
50 return nil, err
51 }
52 req.Header.Set("Authorization", "Bearer "+accessToken)
53 req.Header.Set("Accept", "image/*")
54 if e.UserAgent != "" {
55 req.Header.Set("User-Agent", e.UserAgent)
56 }
57 res, err := e.graphClient().Do(req)
58 if err != nil {
59 return nil, fmt.Errorf("auth: Graph-foto: %w", err)
60 }
61 defer res.Body.Close()
62 if res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusNoContent {
63 _, _ = io.Copy(io.Discard, io.LimitReader(res.Body, 64<<10))
64 return nil, ErrNoPhoto
65 }
66 data, err := io.ReadAll(io.LimitReader(res.Body, graphPhotoMax+1))
67 if err != nil {
68 return nil, fmt.Errorf("auth: Graph-foto lezen: %w", err)
69 }
70 if len(data) > graphPhotoMax {
71 return nil, fmt.Errorf("auth: Graph-foto te groot")
72 }
73 if res.StatusCode >= 400 {
74 return nil, fmt.Errorf("auth: Graph-foto: %s", res.Status)
75 }
76 if _, _, err := image.Decode(bytes.NewReader(data)); err != nil {
77 return nil, fmt.Errorf("auth: Graph-foto ongeldig: %w", err)
78 }
79 return data, nil
80}
81
82func (e *Entra) graphClient() *http.Client {
83 base := e.HTTP
84 if base == nil {
85 base = &http.Client{Timeout: 15 * time.Second}
86 }
87 c := *base
88 c.CheckRedirect = func(req *http.Request, via []*http.Request) error {
89 if len(via) >= 5 {
90 return fmt.Errorf("auth: te veel redirects")
91 }
92 return e.graphURLOK(req.URL.String())
93 }
94 return &c
95}
96
97func (e *Entra) graphURLOK(raw string) error {
98 u, err := url.Parse(raw)
99 if err != nil || u.Host == "" {
100 return fmt.Errorf("auth: ongeldige Graph-URL")
101 }
102 want, err := url.Parse(e.photoURL())
103 if err != nil || want.Host == "" {
104 return fmt.Errorf("auth: ongeldige Graph-URL")
105 }
106 if !strings.EqualFold(u.Host, want.Host) {
107 return fmt.Errorf("auth: Graph-foto alleen vanaf %s", want.Host)
108 }
109 if e.GraphPhotoURL == "" && u.Scheme != "https" {
110 return fmt.Errorf("auth: Graph-foto moet HTTPS zijn")
111 }
112 if u.Scheme != "https" && u.Scheme != "http" {
113 return fmt.Errorf("auth: ongeldige Graph-URL")
114 }
115 return nil
116}
internal/auth/entra_photo_test.go added +130 −0
@@ -0,0 +1,130 @@
1 package auth
2
3 import (
4 "bytes"
5 "context"
6 "image"
7 "image/color"
8 "image/png"
9 "net/http"
10 "net/http/httptest"
11 "strings"
12 "testing"
13 )
14
15 func TestFetchPhotoOK(t *testing.T) {
16 img := tinyPNG()
17 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
18 if r.URL.Path != "/v1.0/me/photo/$value" {
19 t.Errorf("path %s", r.URL.Path)
20 }
21 if r.Header.Get("Authorization") != "Bearer entra-access" {
22 t.Errorf("auth %q", r.Header.Get("Authorization"))
23 }
24 w.Header().Set("Content-Type", "image/png")
25 _, _ = w.Write(img)
26 }))
27 t.Cleanup(srv.Close)
28 e := NewEntra("https://login.example.test/t/v2.0", "t", "c", "s", "BlueGit-test")
29 e.HTTP = srv.Client()
30 e.GraphPhotoURL = srv.URL + "/v1.0/me/photo/$value"
31 got, err := e.FetchPhoto(context.Background(), "entra-access")
32 if err != nil {
33 t.Fatal(err)
34 }
35 if !bytes.Equal(got, img) {
36 t.Fatalf("bytes %d", len(got))
37 }
38 }
39
40 func TestFetchPhotoNotFound(t *testing.T) {
41 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
42 http.Error(w, `{"error":{"code":"ImageNotFound"}}`, http.StatusNotFound)
43 }))
44 t.Cleanup(srv.Close)
45 e := NewEntra("https://login.example.test/t/v2.0", "t", "c", "s", "BlueGit-test")
46 e.HTTP = srv.Client()
47 e.GraphPhotoURL = srv.URL + "/v1.0/me/photo/$value"
48 _, err := e.FetchPhoto(context.Background(), "entra-access")
49 if err != ErrNoPhoto {
50 t.Fatalf("got %v", err)
51 }
52 }
53
54 func TestFetchPhotoRejectsForeignHost(t *testing.T) {
55 var hit bool
56 foreign := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
57 hit = true
58 w.WriteHeader(http.StatusOK)
59 }))
60 t.Cleanup(foreign.Close)
61 e := NewEntra("https://login.example.test/t/v2.0", "t", "c", "s", "BlueGit-test")
62 e.HTTP = foreign.Client()
63 // Productie-URL: graph.microsoft.com, niet de testhost.
64 _, err := e.FetchPhoto(context.Background(), "entra-access")
65 if err == nil || hit {
66 t.Fatalf("moet vreemde host weigeren, err=%v hit=%v", err, hit)
67 }
68 if !strings.Contains(err.Error(), "graph.microsoft.com") && !strings.Contains(err.Error(), "Graph") {
69 t.Fatalf("fout %v", err)
70 }
71 }
72
73 func TestFetchPhotoRejectsRedirectOffHost(t *testing.T) {
74 var leak bool
75 evil := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
76 leak = true
77 _, _ = w.Write(tinyPNG())
78 }))
79 t.Cleanup(evil.Close)
80 mux := http.NewServeMux()
81 mux.HandleFunc("/v1.0/me/photo/$value", func(w http.ResponseWriter, r *http.Request) {
82 http.Redirect(w, r, evil.URL+"/stolen", http.StatusFound)
83 })
84 srv := httptest.NewServer(mux)
85 t.Cleanup(srv.Close)
86 e := NewEntra("https://login.example.test/t/v2.0", "t", "c", "s", "BlueGit-test")
87 e.HTTP = srv.Client()
88 e.GraphPhotoURL = srv.URL + "/v1.0/me/photo/$value"
89 _, err := e.FetchPhoto(context.Background(), "entra-access")
90 if err == nil || leak {
91 t.Fatalf("redirect naar andere host, err=%v leak=%v", err, leak)
92 }
93 }
94
95 func TestFetchPhotoRejectsInvalidImage(t *testing.T) {
96 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
97 w.Header().Set("Content-Type", "image/png")
98 _, _ = w.Write([]byte("niet-een-plaatje"))
99 }))
100 t.Cleanup(srv.Close)
101 e := NewEntra("https://login.example.test/t/v2.0", "t", "c", "s", "BlueGit-test")
102 e.HTTP = srv.Client()
103 e.GraphPhotoURL = srv.URL + "/v1.0/me/photo/$value"
104 if _, err := e.FetchPhoto(context.Background(), "entra-access"); err == nil {
105 t.Fatal("ongeldig type")
106 }
107 }
108
109 func TestFetchPhotoRejectsTooLarge(t *testing.T) {
110 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
111 w.Header().Set("Content-Type", "application/octet-stream")
112 _, _ = w.Write(bytes.Repeat([]byte("x"), graphPhotoMax+2))
113 }))
114 t.Cleanup(srv.Close)
115 e := NewEntra("https://login.example.test/t/v2.0", "t", "c", "s", "BlueGit-test")
116 e.HTTP = srv.Client()
117 e.GraphPhotoURL = srv.URL + "/v1.0/me/photo/$value"
118 _, err := e.FetchPhoto(context.Background(), "entra-access")
119 if err == nil || !strings.Contains(err.Error(), "groot") {
120 t.Fatalf("grootte %v", err)
121 }
122 }
123
124 func tinyPNG() []byte {
125 img := image.NewNRGBA(image.Rect(0, 0, 2, 2))
126 img.SetNRGBA(0, 0, color.NRGBA{R: 255, A: 255})
127 var buf bytes.Buffer
128 _ = png.Encode(&buf, img)
129 return buf.Bytes()
130 }
@@ -0,0 +1,130 @@
1package auth
2
3import (
4 "bytes"
5 "context"
6 "image"
7 "image/color"
8 "image/png"
9 "net/http"
10 "net/http/httptest"
11 "strings"
12 "testing"
13)
14
15func TestFetchPhotoOK(t *testing.T) {
16 img := tinyPNG()
17 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
18 if r.URL.Path != "/v1.0/me/photo/$value" {
19 t.Errorf("path %s", r.URL.Path)
20 }
21 if r.Header.Get("Authorization") != "Bearer entra-access" {
22 t.Errorf("auth %q", r.Header.Get("Authorization"))
23 }
24 w.Header().Set("Content-Type", "image/png")
25 _, _ = w.Write(img)
26 }))
27 t.Cleanup(srv.Close)
28 e := NewEntra("https://login.example.test/t/v2.0", "t", "c", "s", "BlueGit-test")
29 e.HTTP = srv.Client()
30 e.GraphPhotoURL = srv.URL + "/v1.0/me/photo/$value"
31 got, err := e.FetchPhoto(context.Background(), "entra-access")
32 if err != nil {
33 t.Fatal(err)
34 }
35 if !bytes.Equal(got, img) {
36 t.Fatalf("bytes %d", len(got))
37 }
38}
39
40func TestFetchPhotoNotFound(t *testing.T) {
41 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
42 http.Error(w, `{"error":{"code":"ImageNotFound"}}`, http.StatusNotFound)
43 }))
44 t.Cleanup(srv.Close)
45 e := NewEntra("https://login.example.test/t/v2.0", "t", "c", "s", "BlueGit-test")
46 e.HTTP = srv.Client()
47 e.GraphPhotoURL = srv.URL + "/v1.0/me/photo/$value"
48 _, err := e.FetchPhoto(context.Background(), "entra-access")
49 if err != ErrNoPhoto {
50 t.Fatalf("got %v", err)
51 }
52}
53
54func TestFetchPhotoRejectsForeignHost(t *testing.T) {
55 var hit bool
56 foreign := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
57 hit = true
58 w.WriteHeader(http.StatusOK)
59 }))
60 t.Cleanup(foreign.Close)
61 e := NewEntra("https://login.example.test/t/v2.0", "t", "c", "s", "BlueGit-test")
62 e.HTTP = foreign.Client()
63 // Productie-URL: graph.microsoft.com, niet de testhost.
64 _, err := e.FetchPhoto(context.Background(), "entra-access")
65 if err == nil || hit {
66 t.Fatalf("moet vreemde host weigeren, err=%v hit=%v", err, hit)
67 }
68 if !strings.Contains(err.Error(), "graph.microsoft.com") && !strings.Contains(err.Error(), "Graph") {
69 t.Fatalf("fout %v", err)
70 }
71}
72
73func TestFetchPhotoRejectsRedirectOffHost(t *testing.T) {
74 var leak bool
75 evil := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
76 leak = true
77 _, _ = w.Write(tinyPNG())
78 }))
79 t.Cleanup(evil.Close)
80 mux := http.NewServeMux()
81 mux.HandleFunc("/v1.0/me/photo/$value", func(w http.ResponseWriter, r *http.Request) {
82 http.Redirect(w, r, evil.URL+"/stolen", http.StatusFound)
83 })
84 srv := httptest.NewServer(mux)
85 t.Cleanup(srv.Close)
86 e := NewEntra("https://login.example.test/t/v2.0", "t", "c", "s", "BlueGit-test")
87 e.HTTP = srv.Client()
88 e.GraphPhotoURL = srv.URL + "/v1.0/me/photo/$value"
89 _, err := e.FetchPhoto(context.Background(), "entra-access")
90 if err == nil || leak {
91 t.Fatalf("redirect naar andere host, err=%v leak=%v", err, leak)
92 }
93}
94
95func TestFetchPhotoRejectsInvalidImage(t *testing.T) {
96 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
97 w.Header().Set("Content-Type", "image/png")
98 _, _ = w.Write([]byte("niet-een-plaatje"))
99 }))
100 t.Cleanup(srv.Close)
101 e := NewEntra("https://login.example.test/t/v2.0", "t", "c", "s", "BlueGit-test")
102 e.HTTP = srv.Client()
103 e.GraphPhotoURL = srv.URL + "/v1.0/me/photo/$value"
104 if _, err := e.FetchPhoto(context.Background(), "entra-access"); err == nil {
105 t.Fatal("ongeldig type")
106 }
107}
108
109func TestFetchPhotoRejectsTooLarge(t *testing.T) {
110 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
111 w.Header().Set("Content-Type", "application/octet-stream")
112 _, _ = w.Write(bytes.Repeat([]byte("x"), graphPhotoMax+2))
113 }))
114 t.Cleanup(srv.Close)
115 e := NewEntra("https://login.example.test/t/v2.0", "t", "c", "s", "BlueGit-test")
116 e.HTTP = srv.Client()
117 e.GraphPhotoURL = srv.URL + "/v1.0/me/photo/$value"
118 _, err := e.FetchPhoto(context.Background(), "entra-access")
119 if err == nil || !strings.Contains(err.Error(), "groot") {
120 t.Fatalf("grootte %v", err)
121 }
122}
123
124func tinyPNG() []byte {
125 img := image.NewNRGBA(image.Rect(0, 0, 2, 2))
126 img.SetNRGBA(0, 0, color.NRGBA{R: 255, A: 255})
127 var buf bytes.Buffer
128 _ = png.Encode(&buf, img)
129 return buf.Bytes()
130}
internal/auth/entra_test.go +1 −1
@@ -106,7 +106,7 @@ func TestEntraExchangeWithFakeOIDC(t *testing.T) {
106 106
107 107 challenge := PKCEChallenge(verifier)
108 108 url := client.AuthorizeURL("state-1", nonce, "https://git.example.test/auth/callback", challenge)
109 if !strings.Contains(url, "/authorize?") || !strings.Contains(url, "nonce="+nonce) || !strings.Contains(url, "scope=openid+profile+email") {
109 if !strings.Contains(url, "/authorize?") || !strings.Contains(url, "nonce="+nonce) || !strings.Contains(url, "scope=openid+profile+email+User.Read") {
110 110 t.Fatal(url)
111 111 }
112 112 if !strings.Contains(url, "code_challenge="+challenge) || !strings.Contains(url, "code_challenge_method=S256") {
@@ -106,7 +106,7 @@ func TestEntraExchangeWithFakeOIDC(t *testing.T) {
106
106
107 challenge := PKCEChallenge(verifier)
107 challenge := PKCEChallenge(verifier)
108 url := client.AuthorizeURL("state-1", nonce, "https://git.example.test/auth/callback", challenge)
108 url := client.AuthorizeURL("state-1", nonce, "https://git.example.test/auth/callback", challenge)
109 if !strings.Contains(url, "/authorize?") || !strings.Contains(url, "nonce="+nonce) || !strings.Contains(url, "scope=openid+profile+email") {
109 if !strings.Contains(url, "/authorize?") || !strings.Contains(url, "nonce="+nonce) || !strings.Contains(url, "scope=openid+profile+email+User.Read") {
110 t.Fatal(url)
110 t.Fatal(url)
111 }
111 }
112 if !strings.Contains(url, "code_challenge="+challenge) || !strings.Contains(url, "code_challenge_method=S256") {
112 if !strings.Contains(url, "code_challenge="+challenge) || !strings.Contains(url, "code_challenge_method=S256") {
internal/gitrepo/repo.go +19 −0
@@ -300,6 +300,25 @@ func Branches(ctx context.Context, gitBin, dir string) ([]string, error) {
300 300 return names, nil
301 301 }
302 302
303 // SetHEAD zet de symbolische HEAD van een bare repository naar een bestaande branch.
304 // Het verwijdert geen refs of objecten.
305 func SetHEAD(ctx context.Context, gitBin, dir, branch string) error {
306 if branch == "" {
307 return fmt.Errorf("leeg branch")
308 }
309 _, err := run(ctx, gitBin, nil, "-C", dir, "symbolic-ref", "HEAD", "refs/heads/"+branch)
310 return err
311 }
312
313 // HasBranch meldt of de named branch bestaat.
314 func HasBranch(ctx context.Context, gitBin, dir, branch string) bool {
315 if branch == "" {
316 return false
317 }
318 _, err := run(ctx, gitBin, nil, "-C", dir, "show-ref", "--verify", "--quiet", "refs/heads/"+branch)
319 return err == nil
320 }
321
303 322 // HasCommit meldt of sha een commit in deze repository is.
304 323 func HasCommit(ctx context.Context, gitBin, dir, sha string) bool {
305 324 out, err := run(ctx, gitBin, nil, "-C", dir, "cat-file", "-t", sha)
@@ -300,6 +300,25 @@ func Branches(ctx context.Context, gitBin, dir string) ([]string, error) {
300 return names, nil
300 return names, nil
301}
301}
302
302
303// SetHEAD zet de symbolische HEAD van een bare repository naar een bestaande branch.
304// Het verwijdert geen refs of objecten.
305func SetHEAD(ctx context.Context, gitBin, dir, branch string) error {
306 if branch == "" {
307 return fmt.Errorf("leeg branch")
308 }
309 _, err := run(ctx, gitBin, nil, "-C", dir, "symbolic-ref", "HEAD", "refs/heads/"+branch)
310 return err
311}
312
313// HasBranch meldt of de named branch bestaat.
314func HasBranch(ctx context.Context, gitBin, dir, branch string) bool {
315 if branch == "" {
316 return false
317 }
318 _, err := run(ctx, gitBin, nil, "-C", dir, "show-ref", "--verify", "--quiet", "refs/heads/"+branch)
319 return err == nil
320}
321
303// HasCommit meldt of sha een commit in deze repository is.
322// HasCommit meldt of sha een commit in deze repository is.
304func HasCommit(ctx context.Context, gitBin, dir, sha string) bool {
323func HasCommit(ctx context.Context, gitBin, dir, sha string) bool {
305 out, err := run(ctx, gitBin, nil, "-C", dir, "cat-file", "-t", sha)
324 out, err := run(ctx, gitBin, nil, "-C", dir, "cat-file", "-t", sha)
internal/i18n/catalog.go +1 −1
@@ -348,7 +348,7 @@ var en = map[string]string{
348 348 "set.ev.release": "release published",
349 349 "set.saveWebhook": "Save webhook",
350 350 "logo.file": "Logo",
351 "logo.hint": "PNG, JPEG, GIF or SVG. Images larger than 512×512 are scaled down.",
351 "logo.hint": "PNG, JPEG, GIF, SVG or ICO. Images larger than 512×512 are scaled down.",
352 352
353 353 "acct.hint": "For git over HTTPS: your username and a token as the password.",
354 354 "acct.tokens": "Access tokens",
@@ -348,7 +348,7 @@ var en = map[string]string{
348 "set.ev.release": "release published",
348 "set.ev.release": "release published",
349 "set.saveWebhook": "Save webhook",
349 "set.saveWebhook": "Save webhook",
350 "logo.file": "Logo",
350 "logo.file": "Logo",
351 "logo.hint": "PNG, JPEG, GIF or SVG. Images larger than 512×512 are scaled down.",
351 "logo.hint": "PNG, JPEG, GIF, SVG or ICO. Images larger than 512×512 are scaled down.",
352
352
353 "acct.hint": "For git over HTTPS: your username and a token as the password.",
353 "acct.hint": "For git over HTTPS: your username and a token as the password.",
354 "acct.tokens": "Access tokens",
354 "acct.tokens": "Access tokens",
internal/i18n/catalog_cipause.go added +24 −0
@@ -0,0 +1,24 @@
1 package i18n
2
3 func init() {
4 addCatalog(en, map[string]string{
5 "ci.pause.label": "Pause CI for this project",
6 "ci.pause.hint": "No new pipelines are queued while this is on (pushes, merge requests and manual runs). Jobs that are already running or queued keep going.",
7 "err.ciPaused": "CI is paused for this project",
8 })
9 addCatalog(nl, map[string]string{
10 "ci.pause.label": "CI voor dit project pauzeren",
11 "ci.pause.hint": "Er worden geen nieuwe pipelines in de wachtrij gezet zolang dit aan staat (pushes, merge requests en handmatige runs). Jobs die al lopen of in de wachtrij staan, lopen wel af.",
12 "err.ciPaused": "CI is gepauzeerd voor dit project",
13 })
14 addCatalog(de, map[string]string{
15 "ci.pause.label": "CI für dieses Projekt anhalten",
16 "ci.pause.hint": "Solange dies an ist, werden keine neuen Pipelines eingereiht (Pushes, Merge Requests und manuelle Starts). Bereits laufende oder wartende Jobs laufen weiter.",
17 "err.ciPaused": "CI ist für dieses Projekt angehalten",
18 })
19 addCatalog(fr, map[string]string{
20 "ci.pause.label": "Mettre la CI de ce projet en pause",
21 "ci.pause.hint": "Aucun nouveau pipeline n’est mis en file tant que cette option est active (poussées, merge requests et lancements manuels). Les jobs déjà en cours ou en file se terminent normalement.",
22 "err.ciPaused": "La CI est en pause pour ce projet",
23 })
24 }
@@ -0,0 +1,24 @@
1package i18n
2
3func init() {
4 addCatalog(en, map[string]string{
5 "ci.pause.label": "Pause CI for this project",
6 "ci.pause.hint": "No new pipelines are queued while this is on (pushes, merge requests and manual runs). Jobs that are already running or queued keep going.",
7 "err.ciPaused": "CI is paused for this project",
8 })
9 addCatalog(nl, map[string]string{
10 "ci.pause.label": "CI voor dit project pauzeren",
11 "ci.pause.hint": "Er worden geen nieuwe pipelines in de wachtrij gezet zolang dit aan staat (pushes, merge requests en handmatige runs). Jobs die al lopen of in de wachtrij staan, lopen wel af.",
12 "err.ciPaused": "CI is gepauzeerd voor dit project",
13 })
14 addCatalog(de, map[string]string{
15 "ci.pause.label": "CI für dieses Projekt anhalten",
16 "ci.pause.hint": "Solange dies an ist, werden keine neuen Pipelines eingereiht (Pushes, Merge Requests und manuelle Starts). Bereits laufende oder wartende Jobs laufen weiter.",
17 "err.ciPaused": "CI ist für dieses Projekt angehalten",
18 })
19 addCatalog(fr, map[string]string{
20 "ci.pause.label": "Mettre la CI de ce projet en pause",
21 "ci.pause.hint": "Aucun nouveau pipeline n’est mis en file tant que cette option est active (poussées, merge requests et lancements manuels). Les jobs déjà en cours ou en file se terminent normalement.",
22 "err.ciPaused": "La CI est en pause pour ce projet",
23 })
24}
internal/i18n/catalog_lang.go +3 −3
@@ -352,7 +352,7 @@ var nl = map[string]string{
352 352 "set.ev.release": "release gepubliceerd",
353 353 "set.saveWebhook": "Webhook opslaan",
354 354 "logo.file": "Logo",
355 "logo.hint": "PNG, JPEG, GIF of SVG. Groter dan 512×512 wordt teruggeschaald.",
355 "logo.hint": "PNG, JPEG, GIF, SVG of ICO. Groter dan 512×512 wordt teruggeschaald.",
356 356 "acct.hint": "Voor git via HTTPS: je gebruikersnaam en een token als wachtwoord.",
357 357 "acct.tokens": "Toegangstokens",
358 358 "acct.tokenName": "naam, bijvoorbeeld laptop",
@@ -1015,7 +1015,7 @@ var de = map[string]string{
1015 1015 "set.ev.release": "Release veröffentlicht",
1016 1016 "set.saveWebhook": "Webhook speichern",
1017 1017 "logo.file": "Logo",
1018 "logo.hint": "PNG, JPEG, GIF oder SVG. Größer als 512×512 wird verkleinert.",
1018 "logo.hint": "PNG, JPEG, GIF, SVG oder ICO. Größer als 512×512 wird verkleinert.",
1019 1019 "acct.hint": "Für Git über HTTPS: dein Benutzername und ein Token als Passwort.",
1020 1020 "acct.tokens": "Zugriffstoken",
1021 1021 "acct.tokenName": "Name, zum Beispiel Laptop",
@@ -1678,7 +1678,7 @@ var fr = map[string]string{
1678 1678 "set.ev.release": "version publiée",
1679 1679 "set.saveWebhook": "Enregistrer le webhook",
1680 1680 "logo.file": "Logo",
1681 "logo.hint": "PNG, JPEG, GIF ou SVG. Au-delà de 512×512, l’image est réduite.",
1681 "logo.hint": "PNG, JPEG, GIF, SVG ou ICO. Au-delà de 512×512, l’image est réduite.",
1682 1682 "acct.hint": "Pour git en HTTPS : ton nom d’utilisateur et un jeton comme mot de passe.",
1683 1683 "acct.tokens": "Jetons d’accès",
1684 1684 "acct.tokenName": "nom, par exemple ordinateur",
@@ -352,7 +352,7 @@ var nl = map[string]string{
352 "set.ev.release": "release gepubliceerd",
352 "set.ev.release": "release gepubliceerd",
353 "set.saveWebhook": "Webhook opslaan",
353 "set.saveWebhook": "Webhook opslaan",
354 "logo.file": "Logo",
354 "logo.file": "Logo",
355 "logo.hint": "PNG, JPEG, GIF of SVG. Groter dan 512×512 wordt teruggeschaald.",
355 "logo.hint": "PNG, JPEG, GIF, SVG of ICO. Groter dan 512×512 wordt teruggeschaald.",
356 "acct.hint": "Voor git via HTTPS: je gebruikersnaam en een token als wachtwoord.",
356 "acct.hint": "Voor git via HTTPS: je gebruikersnaam en een token als wachtwoord.",
357 "acct.tokens": "Toegangstokens",
357 "acct.tokens": "Toegangstokens",
358 "acct.tokenName": "naam, bijvoorbeeld laptop",
358 "acct.tokenName": "naam, bijvoorbeeld laptop",
@@ -1015,7 +1015,7 @@ var de = map[string]string{
1015 "set.ev.release": "Release veröffentlicht",
1015 "set.ev.release": "Release veröffentlicht",
1016 "set.saveWebhook": "Webhook speichern",
1016 "set.saveWebhook": "Webhook speichern",
1017 "logo.file": "Logo",
1017 "logo.file": "Logo",
1018 "logo.hint": "PNG, JPEG, GIF oder SVG. Größer als 512×512 wird verkleinert.",
1018 "logo.hint": "PNG, JPEG, GIF, SVG oder ICO. Größer als 512×512 wird verkleinert.",
1019 "acct.hint": "Für Git über HTTPS: dein Benutzername und ein Token als Passwort.",
1019 "acct.hint": "Für Git über HTTPS: dein Benutzername und ein Token als Passwort.",
1020 "acct.tokens": "Zugriffstoken",
1020 "acct.tokens": "Zugriffstoken",
1021 "acct.tokenName": "Name, zum Beispiel Laptop",
1021 "acct.tokenName": "Name, zum Beispiel Laptop",
@@ -1678,7 +1678,7 @@ var fr = map[string]string{
1678 "set.ev.release": "version publiée",
1678 "set.ev.release": "version publiée",
1679 "set.saveWebhook": "Enregistrer le webhook",
1679 "set.saveWebhook": "Enregistrer le webhook",
1680 "logo.file": "Logo",
1680 "logo.file": "Logo",
1681 "logo.hint": "PNG, JPEG, GIF ou SVG. Au-delà de 512×512, l’image est réduite.",
1681 "logo.hint": "PNG, JPEG, GIF, SVG ou ICO. Au-delà de 512×512, l’image est réduite.",
1682 "acct.hint": "Pour git en HTTPS : ton nom d’utilisateur et un jeton comme mot de passe.",
1682 "acct.hint": "Pour git en HTTPS : ton nom d’utilisateur et un jeton comme mot de passe.",
1683 "acct.tokens": "Jetons d’accès",
1683 "acct.tokens": "Jetons d’accès",
1684 "acct.tokenName": "nom, par exemple ordinateur",
1684 "acct.tokenName": "nom, par exemple ordinateur",
internal/logo/logo.go +35 −0
@@ -5,6 +5,7 @@ package logo
5 5
6 6 import (
7 7 "bytes"
8 "encoding/binary"
8 9 "encoding/xml"
9 10 "fmt"
10 11 "image"
@@ -39,6 +40,12 @@ func Normalize(in []byte) ([]byte, string, error) {
39 40 }
40 41 return in, "image/svg+xml", nil
41 42 }
43 if looksICO(in) {
44 if err := vetICO(in); err != nil {
45 return nil, "", err
46 }
47 return in, "image/x-icon", nil
48 }
42 49 img, _, err := image.Decode(bytes.NewReader(in))
43 50 if err != nil {
44 51 return nil, "", i18n.E("err.logoType")
@@ -177,6 +184,34 @@ func vetSVG(in []byte) error {
177 184 return nil
178 185 }
179 186
187 // looksICO herkent de ICO-kop (reserved=0, type=1). CUR (type=2) wijzen we af.
188 func looksICO(in []byte) bool {
189 return len(in) >= 6 && in[0] == 0 && in[1] == 0 && in[2] == 1 && in[3] == 0
190 }
191
192 func vetICO(in []byte) error {
193 if !looksICO(in) {
194 return i18n.E("err.logoType")
195 }
196 n := int(binary.LittleEndian.Uint16(in[4:6]))
197 if n < 1 || n > 64 {
198 return i18n.E("err.logoType")
199 }
200 need := 6 + n*16
201 if len(in) < need {
202 return i18n.E("err.logoType")
203 }
204 for i := 0; i < n; i++ {
205 ent := in[6+i*16 : 6+(i+1)*16]
206 size := int(binary.LittleEndian.Uint32(ent[8:12]))
207 off := int(binary.LittleEndian.Uint32(ent[12:16]))
208 if size < 1 || off < need || off > len(in) || off+size > len(in) {
209 return i18n.E("err.logoType")
210 }
211 }
212 return nil
213 }
214
180 215 // SizeOf decodes a PNG or other raster and returns its pixel size.
181 216 func SizeOf(in []byte) (int, int, error) {
182 217 cfg, _, err := image.DecodeConfig(bytes.NewReader(in))
@@ -5,6 +5,7 @@ package logo
5
5
6import (
6import (
7 "bytes"
7 "bytes"
8 "encoding/binary"
8 "encoding/xml"
9 "encoding/xml"
9 "fmt"
10 "fmt"
10 "image"
11 "image"
@@ -39,6 +40,12 @@ func Normalize(in []byte) ([]byte, string, error) {
39 }
40 }
40 return in, "image/svg+xml", nil
41 return in, "image/svg+xml", nil
41 }
42 }
43 if looksICO(in) {
44 if err := vetICO(in); err != nil {
45 return nil, "", err
46 }
47 return in, "image/x-icon", nil
48 }
42 img, _, err := image.Decode(bytes.NewReader(in))
49 img, _, err := image.Decode(bytes.NewReader(in))
43 if err != nil {
50 if err != nil {
44 return nil, "", i18n.E("err.logoType")
51 return nil, "", i18n.E("err.logoType")
@@ -177,6 +184,34 @@ func vetSVG(in []byte) error {
177 return nil
184 return nil
178}
185}
179
186
187// looksICO herkent de ICO-kop (reserved=0, type=1). CUR (type=2) wijzen we af.
188func looksICO(in []byte) bool {
189 return len(in) >= 6 && in[0] == 0 && in[1] == 0 && in[2] == 1 && in[3] == 0
190}
191
192func vetICO(in []byte) error {
193 if !looksICO(in) {
194 return i18n.E("err.logoType")
195 }
196 n := int(binary.LittleEndian.Uint16(in[4:6]))
197 if n < 1 || n > 64 {
198 return i18n.E("err.logoType")
199 }
200 need := 6 + n*16
201 if len(in) < need {
202 return i18n.E("err.logoType")
203 }
204 for i := 0; i < n; i++ {
205 ent := in[6+i*16 : 6+(i+1)*16]
206 size := int(binary.LittleEndian.Uint32(ent[8:12]))
207 off := int(binary.LittleEndian.Uint32(ent[12:16]))
208 if size < 1 || off < need || off > len(in) || off+size > len(in) {
209 return i18n.E("err.logoType")
210 }
211 }
212 return nil
213}
214
180// SizeOf decodes a PNG or other raster and returns its pixel size.
215// SizeOf decodes a PNG or other raster and returns its pixel size.
181func SizeOf(in []byte) (int, int, error) {
216func SizeOf(in []byte) (int, int, error) {
182 cfg, _, err := image.DecodeConfig(bytes.NewReader(in))
217 cfg, _, err := image.DecodeConfig(bytes.NewReader(in))
internal/logo/logo_test.go +42 −0
@@ -75,3 +75,45 @@ func solid(w, h int, c color.NRGBA) []byte {
75 75 _ = png.Encode(&buf, img)
76 76 return buf.Bytes()
77 77 }
78
79 func TestICO(t *testing.T) {
80 png := solid(16, 16, color.NRGBA{R: 31, G: 111, B: 235, A: 255})
81 ico := encodeICO(png)
82 out, mime, err := Normalize(ico)
83 if err != nil || mime != "image/x-icon" || !bytes.Equal(out, ico) {
84 t.Fatalf("ico %s %v %d", mime, err, len(out))
85 }
86 if _, _, err := Normalize([]byte{0, 0, 2, 0, 1, 0}); err == nil {
87 t.Fatal("cursor")
88 }
89 if _, _, err := Normalize([]byte{0, 0, 1, 0, 0, 0}); err == nil {
90 t.Fatal("lege ico")
91 }
92 bad := make([]byte, 22)
93 bad[2] = 1
94 bad[4] = 1
95 // size and offset out of range
96 if _, _, err := Normalize(bad); err == nil {
97 t.Fatal("korte ico")
98 }
99 }
100
101 func encodeICO(png []byte) []byte {
102 // ICO met één PNG-afbeelding van 16×16.
103 buf := make([]byte, 6+16+len(png))
104 buf[2] = 1
105 buf[4] = 1
106 buf[6] = 16
107 buf[7] = 16
108 binaryPutU32(buf[14:], uint32(len(png)))
109 binaryPutU32(buf[18:], 22)
110 copy(buf[22:], png)
111 return buf
112 }
113
114 func binaryPutU32(b []byte, v uint32) {
115 b[0] = byte(v)
116 b[1] = byte(v >> 8)
117 b[2] = byte(v >> 16)
118 b[3] = byte(v >> 24)
119 }
@@ -75,3 +75,45 @@ func solid(w, h int, c color.NRGBA) []byte {
75 _ = png.Encode(&buf, img)
75 _ = png.Encode(&buf, img)
76 return buf.Bytes()
76 return buf.Bytes()
77}
77}
78
79func TestICO(t *testing.T) {
80 png := solid(16, 16, color.NRGBA{R: 31, G: 111, B: 235, A: 255})
81 ico := encodeICO(png)
82 out, mime, err := Normalize(ico)
83 if err != nil || mime != "image/x-icon" || !bytes.Equal(out, ico) {
84 t.Fatalf("ico %s %v %d", mime, err, len(out))
85 }
86 if _, _, err := Normalize([]byte{0, 0, 2, 0, 1, 0}); err == nil {
87 t.Fatal("cursor")
88 }
89 if _, _, err := Normalize([]byte{0, 0, 1, 0, 0, 0}); err == nil {
90 t.Fatal("lege ico")
91 }
92 bad := make([]byte, 22)
93 bad[2] = 1
94 bad[4] = 1
95 // size and offset out of range
96 if _, _, err := Normalize(bad); err == nil {
97 t.Fatal("korte ico")
98 }
99}
100
101func encodeICO(png []byte) []byte {
102 // ICO met één PNG-afbeelding van 16×16.
103 buf := make([]byte, 6+16+len(png))
104 buf[2] = 1
105 buf[4] = 1
106 buf[6] = 16
107 buf[7] = 16
108 binaryPutU32(buf[14:], uint32(len(png)))
109 binaryPutU32(buf[18:], 22)
110 copy(buf[22:], png)
111 return buf
112}
113
114func binaryPutU32(b []byte, v uint32) {
115 b[0] = byte(v)
116 b[1] = byte(v >> 8)
117 b[2] = byte(v >> 16)
118 b[3] = byte(v >> 24)
119}
internal/runnercfg/docker.go added +39 −0
@@ -0,0 +1,39 @@
1 package runnercfg
2
3 import (
4 "context"
5 "os/exec"
6 "strings"
7 "time"
8 )
9
10 // DockerStatus is de gezondheid van de Docker-daemon.
11 type DockerStatus struct {
12 Reachable bool `json:"reachable"`
13 Error string `json:"error,omitempty"`
14 }
15
16 // PingDocker praat met de Docker-daemon (`docker info`). Een aanwezige
17 // binary zonder bereikbare daemon is niet reachable.
18 func PingDocker(ctx context.Context, bin string) DockerStatus {
19 if strings.TrimSpace(bin) == "" {
20 bin = "docker"
21 }
22 if _, err := exec.LookPath(bin); err != nil {
23 return DockerStatus{Error: err.Error()}
24 }
25 if ctx == nil {
26 ctx = context.Background()
27 }
28 ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
29 defer cancel()
30 out, err := exec.CommandContext(ctx, bin, "info", "--format", "{{.ServerVersion}}").CombinedOutput()
31 msg := strings.TrimSpace(string(out))
32 if err != nil {
33 if msg == "" {
34 msg = err.Error()
35 }
36 return DockerStatus{Error: msg}
37 }
38 return DockerStatus{Reachable: true}
39 }
@@ -0,0 +1,39 @@
1package runnercfg
2
3import (
4 "context"
5 "os/exec"
6 "strings"
7 "time"
8)
9
10// DockerStatus is de gezondheid van de Docker-daemon.
11type DockerStatus struct {
12 Reachable bool `json:"reachable"`
13 Error string `json:"error,omitempty"`
14}
15
16// PingDocker praat met de Docker-daemon (`docker info`). Een aanwezige
17// binary zonder bereikbare daemon is niet reachable.
18func PingDocker(ctx context.Context, bin string) DockerStatus {
19 if strings.TrimSpace(bin) == "" {
20 bin = "docker"
21 }
22 if _, err := exec.LookPath(bin); err != nil {
23 return DockerStatus{Error: err.Error()}
24 }
25 if ctx == nil {
26 ctx = context.Background()
27 }
28 ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
29 defer cancel()
30 out, err := exec.CommandContext(ctx, bin, "info", "--format", "{{.ServerVersion}}").CombinedOutput()
31 msg := strings.TrimSpace(string(out))
32 if err != nil {
33 if msg == "" {
34 msg = err.Error()
35 }
36 return DockerStatus{Error: msg}
37 }
38 return DockerStatus{Reachable: true}
39}
internal/runnercfg/docker_test.go added +27 −0
@@ -0,0 +1,27 @@
1 package runnercfg
2
3 import (
4 "context"
5 "os"
6 "path/filepath"
7 "testing"
8 )
9
10 func TestPingDockerUnreachable(t *testing.T) {
11 dir := t.TempDir()
12 bin := filepath.Join(dir, "docker")
13 if err := os.WriteFile(bin, []byte("#!/bin/sh\necho boom >&2\nexit 1\n"), 0o755); err != nil {
14 t.Fatal(err)
15 }
16 st := PingDocker(context.Background(), bin)
17 if st.Reachable || st.Error == "" {
18 t.Fatalf("%+v", st)
19 }
20 }
21
22 func TestPingDockerMissingBinary(t *testing.T) {
23 st := PingDocker(context.Background(), filepath.Join(t.TempDir(), "nope"))
24 if st.Reachable || st.Error == "" {
25 t.Fatalf("%+v", st)
26 }
27 }
@@ -0,0 +1,27 @@
1package runnercfg
2
3import (
4 "context"
5 "os"
6 "path/filepath"
7 "testing"
8)
9
10func TestPingDockerUnreachable(t *testing.T) {
11 dir := t.TempDir()
12 bin := filepath.Join(dir, "docker")
13 if err := os.WriteFile(bin, []byte("#!/bin/sh\necho boom >&2\nexit 1\n"), 0o755); err != nil {
14 t.Fatal(err)
15 }
16 st := PingDocker(context.Background(), bin)
17 if st.Reachable || st.Error == "" {
18 t.Fatalf("%+v", st)
19 }
20}
21
22func TestPingDockerMissingBinary(t *testing.T) {
23 st := PingDocker(context.Background(), filepath.Join(t.TempDir(), "nope"))
24 if st.Reachable || st.Error == "" {
25 t.Fatalf("%+v", st)
26 }
27}
internal/runnercfg/handler.go +8 −7
@@ -16,13 +16,14 @@ import (
16 16
17 17 // Status is de kop van het scherm.
18 18 type Status struct {
19 Kind string `json:"kind"` // "standalone" of "builtin"
20 Name string `json:"name"`
21 Version string `json:"version"`
22 ServerURL string `json:"server_url"`
23 Online bool `json:"online"`
24 LastContact time.Time `json:"last_contact,omitempty"`
25 ServerPause bool `json:"server_paused"`
19 Kind string `json:"kind"` // "standalone" of "builtin"
20 Name string `json:"name"`
21 Version string `json:"version"`
22 ServerURL string `json:"server_url"`
23 Online bool `json:"online"`
24 LastContact time.Time `json:"last_contact,omitempty"`
25 ServerPause bool `json:"server_paused"`
26 Docker DockerStatus `json:"docker"`
26 27 }
27 28
28 29 // Handler is de gedeelde webinterface en JSON-API voor runnerbeheer.
@@ -16,13 +16,14 @@ import (
16
16
17// Status is de kop van het scherm.
17// Status is de kop van het scherm.
18type Status struct {
18type Status struct {
19 Kind string `json:"kind"` // "standalone" of "builtin"
19 Kind string `json:"kind"` // "standalone" of "builtin"
20 Name string `json:"name"`
20 Name string `json:"name"`
21 Version string `json:"version"`
21 Version string `json:"version"`
22 ServerURL string `json:"server_url"`
22 ServerURL string `json:"server_url"`
23 Online bool `json:"online"`
23 Online bool `json:"online"`
24 LastContact time.Time `json:"last_contact,omitempty"`
24 LastContact time.Time `json:"last_contact,omitempty"`
25 ServerPause bool `json:"server_paused"`
25 ServerPause bool `json:"server_paused"`
26 Docker DockerStatus `json:"docker"`
26}
27}
27
28
28// Handler is de gedeelde webinterface en JSON-API voor runnerbeheer.
29// Handler is de gedeelde webinterface en JSON-API voor runnerbeheer.
internal/server/admin_runner.go +6 −1
@@ -92,7 +92,12 @@ func (s *Server) RunnerMaintenance(ctx context.Context) {
92 92 }
93 93
94 94 func (s *Server) builtinStatus() runnercfg.Status {
95 st := runnercfg.Status{Kind: "builtin", ServerURL: s.Cfg.BaseURL, Online: s.Runner != nil, LastContact: time.Now()}
95 docker := runnercfg.PingDocker(context.Background(), s.Cfg.CI.Docker)
96 st := runnercfg.Status{
97 Kind: "builtin", ServerURL: s.Cfg.BaseURL,
98 Online: s.Runner != nil && docker.Reachable, LastContact: time.Now(),
99 Docker: docker,
100 }
96 101 if s.Runner != nil {
97 102 st.Name = s.Runner.BuiltinName()
98 103 }
@@ -92,7 +92,12 @@ func (s *Server) RunnerMaintenance(ctx context.Context) {
92}
92}
93
93
94func (s *Server) builtinStatus() runnercfg.Status {
94func (s *Server) builtinStatus() runnercfg.Status {
95 st := runnercfg.Status{Kind: "builtin", ServerURL: s.Cfg.BaseURL, Online: s.Runner != nil, LastContact: time.Now()}
95 docker := runnercfg.PingDocker(context.Background(), s.Cfg.CI.Docker)
96 st := runnercfg.Status{
97 Kind: "builtin", ServerURL: s.Cfg.BaseURL,
98 Online: s.Runner != nil && docker.Reachable, LastContact: time.Now(),
99 Docker: docker,
100 }
96 if s.Runner != nil {
101 if s.Runner != nil {
97 st.Name = s.Runner.BuiltinName()
102 st.Name = s.Runner.BuiltinName()
98 }
103 }
internal/server/api_collab.go +13 −1
@@ -21,7 +21,7 @@ func projectJSON(repo store.Repo) map[string]any {
21 21 return map[string]any{
22 22 "id": repo.ID, "path": repo.FullPath(), "name": repo.Name, "owner": repo.OwnerPath,
23 23 "description": repo.Description, "visibility": repo.Visibility, "default_branch": repo.DefaultBranch,
24 "release_visibility": repo.ReleaseVisibility,
24 "release_visibility": repo.ReleaseVisibility, "ci_paused": repo.CIPaused,
25 25 }
26 26 }
27 27
@@ -255,6 +255,8 @@ func (s *Server) apiPutProject(w http.ResponseWriter, r *http.Request) {
255 255 Visibility *string `json:"visibility"`
256 256 ReleaseVisibility *string `json:"release_visibility"`
257 257 StaleManualDays *int `json:"stale_manual_days"`
258 DefaultBranch *string `json:"default_branch"`
259 CIPaused *bool `json:"ci_paused"`
258 260 }
259 261 if err := readJSON(r, &body); err != nil {
260 262 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
@@ -289,6 +291,16 @@ func (s *Server) apiPutProject(w http.ResponseWriter, r *http.Request) {
289 291 return
290 292 }
291 293 }
294 if body.DefaultBranch != nil {
295 if !s.apiOK(w, r, s.opSetDefaultBranch(r.Context(), apiUser(r), repo, *body.DefaultBranch)) {
296 return
297 }
298 }
299 if body.CIPaused != nil {
300 if !s.apiOK(w, r, s.opSetRepoCIPaused(r.Context(), apiUser(r), repo, *body.CIPaused)) {
301 return
302 }
303 }
292 304 repo, _ = s.Store.RepoByPath(r.Context(), repo.OwnerPath, repo.Name)
293 305 writeJSON(w, http.StatusOK, s.projectJSONFull(r, repo))
294 306 }
@@ -21,7 +21,7 @@ func projectJSON(repo store.Repo) map[string]any {
21 return map[string]any{
21 return map[string]any{
22 "id": repo.ID, "path": repo.FullPath(), "name": repo.Name, "owner": repo.OwnerPath,
22 "id": repo.ID, "path": repo.FullPath(), "name": repo.Name, "owner": repo.OwnerPath,
23 "description": repo.Description, "visibility": repo.Visibility, "default_branch": repo.DefaultBranch,
23 "description": repo.Description, "visibility": repo.Visibility, "default_branch": repo.DefaultBranch,
24 "release_visibility": repo.ReleaseVisibility,
24 "release_visibility": repo.ReleaseVisibility, "ci_paused": repo.CIPaused,
25 }
25 }
26}
26}
27
27
@@ -255,6 +255,8 @@ func (s *Server) apiPutProject(w http.ResponseWriter, r *http.Request) {
255 Visibility *string `json:"visibility"`
255 Visibility *string `json:"visibility"`
256 ReleaseVisibility *string `json:"release_visibility"`
256 ReleaseVisibility *string `json:"release_visibility"`
257 StaleManualDays *int `json:"stale_manual_days"`
257 StaleManualDays *int `json:"stale_manual_days"`
258 DefaultBranch *string `json:"default_branch"`
259 CIPaused *bool `json:"ci_paused"`
258 }
260 }
259 if err := readJSON(r, &body); err != nil {
261 if err := readJSON(r, &body); err != nil {
260 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
262 s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
@@ -289,6 +291,16 @@ func (s *Server) apiPutProject(w http.ResponseWriter, r *http.Request) {
289 return
291 return
290 }
292 }
291 }
293 }
294 if body.DefaultBranch != nil {
295 if !s.apiOK(w, r, s.opSetDefaultBranch(r.Context(), apiUser(r), repo, *body.DefaultBranch)) {
296 return
297 }
298 }
299 if body.CIPaused != nil {
300 if !s.apiOK(w, r, s.opSetRepoCIPaused(r.Context(), apiUser(r), repo, *body.CIPaused)) {
301 return
302 }
303 }
292 repo, _ = s.Store.RepoByPath(r.Context(), repo.OwnerPath, repo.Name)
304 repo, _ = s.Store.RepoByPath(r.Context(), repo.OwnerPath, repo.Name)
293 writeJSON(w, http.StatusOK, s.projectJSONFull(r, repo))
305 writeJSON(w, http.StatusOK, s.projectJSONFull(r, repo))
294}
306}
internal/server/api_openapi.go +63 −2
@@ -13,9 +13,15 @@ func decorateAPI(paths map[string]map[string]any, schemas map[string]any) {
13 13 continue
14 14 }
15 15 if b.body != "" {
16 content := jsonSchema(schemaRef(b.body))
17 if b.multipart {
18 content = map[string]any{
19 "multipart/form-data": map[string]any{"schema": schemaRef(b.body)},
20 }
21 }
16 22 op["requestBody"] = map[string]any{
17 23 "required": true,
18 "content": jsonSchema(schemaRef(b.body)),
24 "content": content,
19 25 }
20 26 }
21 27 responses, _ := op["responses"].(map[string]any)
@@ -76,7 +82,7 @@ func jsonSchema(schema map[string]any) map[string]any {
76 82
77 83 type apiBind struct {
78 84 path, method, body, resp, code string
79 array, empty bool
85 array, empty, multipart bool
80 86 }
81 87
82 88 func apiBinds() []apiBind {
@@ -147,6 +153,14 @@ func apiBinds() []apiBind {
147 153 {path: "/projects/{owner}/{repo}/webhooks/{id}", method: "PATCH", code: "200", body: "WebhookUpdate", resp: "Webhook"},
148 154 {path: "/projects/{owner}/{repo}/webhooks/{id}", method: "DELETE", code: "204", empty: true},
149 155 {path: "/projects/{owner}/{repo}/webhooks/{id}/copy", method: "POST", code: "201", body: "WebhookCopy", resp: "WebhookCopyResult"},
156
157 {path: "/projects", method: "POST", code: "201", body: "ProjectCreate", resp: "Project"},
158 {path: "/projects/{owner}/{repo}", method: "PUT", code: "200", body: "ProjectUpdate", resp: "Project"},
159 {path: "/projects/{owner}/{repo}/logo", method: "POST", code: "200", body: "LogoUpload", resp: "LogoResult", multipart: true},
160 {path: "/groups/{path}/logo", method: "POST", code: "200", body: "LogoUpload", resp: "LogoResult", multipart: true},
161 {path: "/projects/{owner}/{repo}/protected_branches", method: "POST", code: "201", body: "ProtectedPattern", resp: "ProtectedPattern"},
162 {path: "/projects/{owner}/{repo}/protected_tags", method: "POST", code: "201", body: "ProtectedPattern", resp: "ProtectedPattern"},
163 {path: "/projects/{owner}/{repo}/ci/lint", method: "POST", code: "200", body: "CILint", resp: "CILintResult"},
150 164 }
151 165 }
152 166
@@ -458,6 +472,53 @@ func apiSchemas() map[string]any {
458 472 "copied_secrets": strArr("Names of secrets copied to the target."),
459 473 "missing_secrets": strArr("Referenced secret names found nowhere; add them in the target."),
460 474 }),
475 "Project": obj("A project.", map[string]any{
476 "id": integer("Internal id."),
477 "path": str("owner/name."),
478 "name": str("Project name."),
479 "owner": str("User or group path."),
480 "description": str("Description."),
481 "visibility": str("public or private."),
482 "default_branch": str("Default branch (symbolic HEAD)."),
483 "release_visibility": str("inherit, private or public."),
484 "ci_paused": boolean("When true, no new pipelines are queued."),
485 "stale_manual_days": integer("Override for expiring manual jobs. -1 inherits the instance setting. Only in the get/update response."),
486 }),
487 "ProjectCreate": obj("Create a project.", map[string]any{
488 "name": str("Project name. Required."),
489 "description": str("Description."),
490 "group": str("Group path. Empty: under your account."),
491 "visibility": str("public or private."),
492 "initialize_with_readme": boolean("Create an initial README commit."),
493 }),
494 "ProjectUpdate": obj("Fields to change on a project. Omitted fields stay unchanged.", map[string]any{
495 "description": str("Description."),
496 "visibility": str("public or private."),
497 "release_visibility": str("inherit, private or public."),
498 "stale_manual_days": integer("Override for expiring manual jobs. -1 inherits the instance setting."),
499 "default_branch": str("Existing branch to make the default. Updates symbolic HEAD and the stored default."),
500 "ci_paused": boolean("When true, no new pipelines are queued (pushes, merge requests, manual runs). Already running or queued jobs keep going."),
501 }),
502 "LogoUpload": obj("Multipart logo upload. Field name is logo. PNG, JPEG, GIF, SVG or ICO.", map[string]any{
503 "logo": map[string]any{"type": "string", "format": "binary", "description": "Logo file."},
504 }),
505 "LogoResult": obj("Logo stored.", map[string]any{"logo": boolean("True when the logo was saved.")}),
506 "ProtectedPattern": obj("A protected branch or tag pattern.", map[string]any{
507 "pattern": str("Git ref pattern to protect."),
508 }),
509 "CILint": obj("Lint a CI file. Provide body, or ref to read blue-ci-cd.yml from the repository.", map[string]any{
510 "body": str("CI YAML to lint. Empty: use the file at ref."),
511 "ref": str("Branch, tag or commit to read the CI file from when body is empty."),
512 }),
513 "CILintResult": obj("Lint result.", map[string]any{
514 "status": str("Human-readable status."),
515 "statusClass": str("CSS class for the status."),
516 "errors": strArr("Errors."),
517 "warnings": strArr("Warnings."),
518 "issues": integer("Number of issues."),
519 "lines": strArr("Rendered source lines."),
520 "bad": map[string]any{"type": "array", "items": integer("1-based line number."), "description": "Lines with errors."},
521 }),
461 522 }
462 523 }
463 524
@@ -13,9 +13,15 @@ func decorateAPI(paths map[string]map[string]any, schemas map[string]any) {
13 continue
13 continue
14 }
14 }
15 if b.body != "" {
15 if b.body != "" {
16 content := jsonSchema(schemaRef(b.body))
17 if b.multipart {
18 content = map[string]any{
19 "multipart/form-data": map[string]any{"schema": schemaRef(b.body)},
20 }
21 }
16 op["requestBody"] = map[string]any{
22 op["requestBody"] = map[string]any{
17 "required": true,
23 "required": true,
18 "content": jsonSchema(schemaRef(b.body)),
24 "content": content,
19 }
25 }
20 }
26 }
21 responses, _ := op["responses"].(map[string]any)
27 responses, _ := op["responses"].(map[string]any)
@@ -76,7 +82,7 @@ func jsonSchema(schema map[string]any) map[string]any {
76
82
77type apiBind struct {
83type apiBind struct {
78 path, method, body, resp, code string
84 path, method, body, resp, code string
79 array, empty bool
85 array, empty, multipart bool
80}
86}
81
87
82func apiBinds() []apiBind {
88func apiBinds() []apiBind {
@@ -147,6 +153,14 @@ func apiBinds() []apiBind {
147 {path: "/projects/{owner}/{repo}/webhooks/{id}", method: "PATCH", code: "200", body: "WebhookUpdate", resp: "Webhook"},
153 {path: "/projects/{owner}/{repo}/webhooks/{id}", method: "PATCH", code: "200", body: "WebhookUpdate", resp: "Webhook"},
148 {path: "/projects/{owner}/{repo}/webhooks/{id}", method: "DELETE", code: "204", empty: true},
154 {path: "/projects/{owner}/{repo}/webhooks/{id}", method: "DELETE", code: "204", empty: true},
149 {path: "/projects/{owner}/{repo}/webhooks/{id}/copy", method: "POST", code: "201", body: "WebhookCopy", resp: "WebhookCopyResult"},
155 {path: "/projects/{owner}/{repo}/webhooks/{id}/copy", method: "POST", code: "201", body: "WebhookCopy", resp: "WebhookCopyResult"},
156
157 {path: "/projects", method: "POST", code: "201", body: "ProjectCreate", resp: "Project"},
158 {path: "/projects/{owner}/{repo}", method: "PUT", code: "200", body: "ProjectUpdate", resp: "Project"},
159 {path: "/projects/{owner}/{repo}/logo", method: "POST", code: "200", body: "LogoUpload", resp: "LogoResult", multipart: true},
160 {path: "/groups/{path}/logo", method: "POST", code: "200", body: "LogoUpload", resp: "LogoResult", multipart: true},
161 {path: "/projects/{owner}/{repo}/protected_branches", method: "POST", code: "201", body: "ProtectedPattern", resp: "ProtectedPattern"},
162 {path: "/projects/{owner}/{repo}/protected_tags", method: "POST", code: "201", body: "ProtectedPattern", resp: "ProtectedPattern"},
163 {path: "/projects/{owner}/{repo}/ci/lint", method: "POST", code: "200", body: "CILint", resp: "CILintResult"},
150 }
164 }
151}
165}
152
166
@@ -458,6 +472,53 @@ func apiSchemas() map[string]any {
458 "copied_secrets": strArr("Names of secrets copied to the target."),
472 "copied_secrets": strArr("Names of secrets copied to the target."),
459 "missing_secrets": strArr("Referenced secret names found nowhere; add them in the target."),
473 "missing_secrets": strArr("Referenced secret names found nowhere; add them in the target."),
460 }),
474 }),
475 "Project": obj("A project.", map[string]any{
476 "id": integer("Internal id."),
477 "path": str("owner/name."),
478 "name": str("Project name."),
479 "owner": str("User or group path."),
480 "description": str("Description."),
481 "visibility": str("public or private."),
482 "default_branch": str("Default branch (symbolic HEAD)."),
483 "release_visibility": str("inherit, private or public."),
484 "ci_paused": boolean("When true, no new pipelines are queued."),
485 "stale_manual_days": integer("Override for expiring manual jobs. -1 inherits the instance setting. Only in the get/update response."),
486 }),
487 "ProjectCreate": obj("Create a project.", map[string]any{
488 "name": str("Project name. Required."),
489 "description": str("Description."),
490 "group": str("Group path. Empty: under your account."),
491 "visibility": str("public or private."),
492 "initialize_with_readme": boolean("Create an initial README commit."),
493 }),
494 "ProjectUpdate": obj("Fields to change on a project. Omitted fields stay unchanged.", map[string]any{
495 "description": str("Description."),
496 "visibility": str("public or private."),
497 "release_visibility": str("inherit, private or public."),
498 "stale_manual_days": integer("Override for expiring manual jobs. -1 inherits the instance setting."),
499 "default_branch": str("Existing branch to make the default. Updates symbolic HEAD and the stored default."),
500 "ci_paused": boolean("When true, no new pipelines are queued (pushes, merge requests, manual runs). Already running or queued jobs keep going."),
501 }),
502 "LogoUpload": obj("Multipart logo upload. Field name is logo. PNG, JPEG, GIF, SVG or ICO.", map[string]any{
503 "logo": map[string]any{"type": "string", "format": "binary", "description": "Logo file."},
504 }),
505 "LogoResult": obj("Logo stored.", map[string]any{"logo": boolean("True when the logo was saved.")}),
506 "ProtectedPattern": obj("A protected branch or tag pattern.", map[string]any{
507 "pattern": str("Git ref pattern to protect."),
508 }),
509 "CILint": obj("Lint a CI file. Provide body, or ref to read blue-ci-cd.yml from the repository.", map[string]any{
510 "body": str("CI YAML to lint. Empty: use the file at ref."),
511 "ref": str("Branch, tag or commit to read the CI file from when body is empty."),
512 }),
513 "CILintResult": obj("Lint result.", map[string]any{
514 "status": str("Human-readable status."),
515 "statusClass": str("CSS class for the status."),
516 "errors": strArr("Errors."),
517 "warnings": strArr("Warnings."),
518 "issues": integer("Number of issues."),
519 "lines": strArr("Rendered source lines."),
520 "bad": map[string]any{"type": "array", "items": integer("1-based line number."), "description": "Lines with errors."},
521 }),
461 }
522 }
462}
523}
463
524
internal/server/api_openapi_test.go +83 −0
@@ -184,3 +184,86 @@ func operation(t *testing.T, paths map[string]any, path, method string) map[stri
184 184 }
185 185 return op
186 186 }
187
188 func TestOpenAPIProjectRequestBodies(t *testing.T) {
189 doc := openAPIDoc()
190 paths := doc["paths"].(map[string]any)
191 assertBody(t, paths, "/projects", "post", "ProjectCreate")
192 assertBody(t, paths, "/projects/{owner}/{repo}", "put", "ProjectUpdate")
193 assertBody(t, paths, "/projects/{owner}/{repo}/protected_branches", "post", "ProtectedPattern")
194 assertBody(t, paths, "/projects/{owner}/{repo}/ci/lint", "post", "CILint")
195 assertResp(t, paths, "/projects", "post", "201", "#/components/schemas/Project")
196 assertResp(t, paths, "/projects/{owner}/{repo}", "put", "200", "#/components/schemas/Project")
197
198 op := paths["/projects/{owner}/{repo}/logo"].(map[string]any)["post"].(map[string]any)
199 body := op["requestBody"].(map[string]any)
200 content := body["content"].(map[string]any)
201 if _, ok := content["multipart/form-data"]; !ok {
202 t.Fatal("logo requestBody moet multipart/form-data zijn")
203 }
204 ref := content["multipart/form-data"].(map[string]any)["schema"].(map[string]any)["$ref"].(string)
205 if ref != "#/components/schemas/LogoUpload" {
206 t.Fatalf("logo schema %s", ref)
207 }
208
209 // Andere POST/PUT/PATCH zonder request-body: alleen acties zonder JSON-veld.
210 allow := map[string]bool{
211 "POST /projects/{owner}/{repo}/star": true,
212 "POST /projects/{owner}/{repo}/pipelines/{id}/cancel": true,
213 "POST /projects/{owner}/{repo}/pipelines/{id}/jobs/{job}/play": true,
214 "POST /projects/{owner}/{repo}/pipelines/{id}/jobs/{job}/retry": true,
215 "POST /projects/{owner}/{repo}/pipelines/{id}/jobs/{job}/cancel": true,
216 "POST /admin/runner/pause": true,
217 "POST /admin/runner/resume": true,
218 "POST /admin/runners/{id}/pause": true,
219 "POST /admin/runners/{id}/resume": true,
220 "POST /user/runners/{id}/pause": true,
221 "POST /user/runners/{id}/resume": true,
222 "POST /groups/{path}/runners/{id}/pause": true,
223 "POST /groups/{path}/runners/{id}/resume": true,
224 "POST /admin/pipelines/expire-stale": true,
225 "POST /admin/self-update/force": true,
226 "POST /admin/cache/clear": true,
227 "POST /admin/git-maintenance": false, // heeft optionele body; mag ontbreken of staan
228 }
229 _ = allow
230 var missing []string
231 for path, item := range paths {
232 ops, _ := item.(map[string]any)
233 for method, raw := range ops {
234 m := strings.ToUpper(method)
235 if m != "POST" && m != "PUT" && m != "PATCH" {
236 continue
237 }
238 op, _ := raw.(map[string]any)
239 if op == nil {
240 continue
241 }
242 key := m + " " + path
243 if allow[key] {
244 continue
245 }
246 if _, ok := op["requestBody"]; !ok {
247 missing = append(missing, key)
248 }
249 }
250 }
251 // Rapporteer alleen de eerder ontbrekende, plus duidelijke schrijf-endpoints
252 // die we nu vullen. Andere actie-POST's zonder body zijn toegestaan.
253 need := []string{
254 "POST /projects",
255 "PUT /projects/{owner}/{repo}",
256 "POST /projects/{owner}/{repo}/logo",
257 "POST /projects/{owner}/{repo}/protected_branches",
258 "POST /projects/{owner}/{repo}/ci/lint",
259 }
260 has := map[string]bool{}
261 for _, k := range missing {
262 has[k] = true
263 }
264 for _, k := range need {
265 if has[k] {
266 t.Errorf("requestBody ontbreekt: %s", k)
267 }
268 }
269 }
@@ -184,3 +184,86 @@ func operation(t *testing.T, paths map[string]any, path, method string) map[stri
184 }
184 }
185 return op
185 return op
186}
186}
187
188func TestOpenAPIProjectRequestBodies(t *testing.T) {
189 doc := openAPIDoc()
190 paths := doc["paths"].(map[string]any)
191 assertBody(t, paths, "/projects", "post", "ProjectCreate")
192 assertBody(t, paths, "/projects/{owner}/{repo}", "put", "ProjectUpdate")
193 assertBody(t, paths, "/projects/{owner}/{repo}/protected_branches", "post", "ProtectedPattern")
194 assertBody(t, paths, "/projects/{owner}/{repo}/ci/lint", "post", "CILint")
195 assertResp(t, paths, "/projects", "post", "201", "#/components/schemas/Project")
196 assertResp(t, paths, "/projects/{owner}/{repo}", "put", "200", "#/components/schemas/Project")
197
198 op := paths["/projects/{owner}/{repo}/logo"].(map[string]any)["post"].(map[string]any)
199 body := op["requestBody"].(map[string]any)
200 content := body["content"].(map[string]any)
201 if _, ok := content["multipart/form-data"]; !ok {
202 t.Fatal("logo requestBody moet multipart/form-data zijn")
203 }
204 ref := content["multipart/form-data"].(map[string]any)["schema"].(map[string]any)["$ref"].(string)
205 if ref != "#/components/schemas/LogoUpload" {
206 t.Fatalf("logo schema %s", ref)
207 }
208
209 // Andere POST/PUT/PATCH zonder request-body: alleen acties zonder JSON-veld.
210 allow := map[string]bool{
211 "POST /projects/{owner}/{repo}/star": true,
212 "POST /projects/{owner}/{repo}/pipelines/{id}/cancel": true,
213 "POST /projects/{owner}/{repo}/pipelines/{id}/jobs/{job}/play": true,
214 "POST /projects/{owner}/{repo}/pipelines/{id}/jobs/{job}/retry": true,
215 "POST /projects/{owner}/{repo}/pipelines/{id}/jobs/{job}/cancel": true,
216 "POST /admin/runner/pause": true,
217 "POST /admin/runner/resume": true,
218 "POST /admin/runners/{id}/pause": true,
219 "POST /admin/runners/{id}/resume": true,
220 "POST /user/runners/{id}/pause": true,
221 "POST /user/runners/{id}/resume": true,
222 "POST /groups/{path}/runners/{id}/pause": true,
223 "POST /groups/{path}/runners/{id}/resume": true,
224 "POST /admin/pipelines/expire-stale": true,
225 "POST /admin/self-update/force": true,
226 "POST /admin/cache/clear": true,
227 "POST /admin/git-maintenance": false, // heeft optionele body; mag ontbreken of staan
228 }
229 _ = allow
230 var missing []string
231 for path, item := range paths {
232 ops, _ := item.(map[string]any)
233 for method, raw := range ops {
234 m := strings.ToUpper(method)
235 if m != "POST" && m != "PUT" && m != "PATCH" {
236 continue
237 }
238 op, _ := raw.(map[string]any)
239 if op == nil {
240 continue
241 }
242 key := m + " " + path
243 if allow[key] {
244 continue
245 }
246 if _, ok := op["requestBody"]; !ok {
247 missing = append(missing, key)
248 }
249 }
250 }
251 // Rapporteer alleen de eerder ontbrekende, plus duidelijke schrijf-endpoints
252 // die we nu vullen. Andere actie-POST's zonder body zijn toegestaan.
253 need := []string{
254 "POST /projects",
255 "PUT /projects/{owner}/{repo}",
256 "POST /projects/{owner}/{repo}/logo",
257 "POST /projects/{owner}/{repo}/protected_branches",
258 "POST /projects/{owner}/{repo}/ci/lint",
259 }
260 has := map[string]bool{}
261 for _, k := range missing {
262 has[k] = true
263 }
264 for _, k := range need {
265 if has[k] {
266 t.Errorf("requestBody ontbreekt: %s", k)
267 }
268 }
269}
internal/server/auth_handlers.go +1 −0
@@ -101,6 +101,7 @@ func (s *Server) finishLogin(w http.ResponseWriter, r *http.Request, authID int6
101 101 http.Error(w, err.Error(), http.StatusBadRequest)
102 102 return
103 103 }
104 user = s.maybeRefreshEntraAvatar(r.Context(), user, token)
104 105 exp := time.Now().Add(time.Duration(expiresIn) * time.Second)
105 106 sess, err := s.Store.CreateSession(r.Context(), user.ID, token, exp)
106 107 if err != nil {
@@ -101,6 +101,7 @@ func (s *Server) finishLogin(w http.ResponseWriter, r *http.Request, authID int6
101 http.Error(w, err.Error(), http.StatusBadRequest)
101 http.Error(w, err.Error(), http.StatusBadRequest)
102 return
102 return
103 }
103 }
104 user = s.maybeRefreshEntraAvatar(r.Context(), user, token)
104 exp := time.Now().Add(time.Duration(expiresIn) * time.Second)
105 exp := time.Now().Add(time.Duration(expiresIn) * time.Second)
105 sess, err := s.Store.CreateSession(r.Context(), user.ID, token, exp)
106 sess, err := s.Store.CreateSession(r.Context(), user.ID, token, exp)
106 if err != nil {
107 if err != nil {
internal/server/events.go +6 −0
@@ -142,6 +142,12 @@ func (s *Server) startPipeline(ctx context.Context, repo store.Repo, sha, ref, a
142 142 if !s.Cfg.CI.Enabled || s.StoragePath() == "" {
143 143 return 0
144 144 }
145 if repo.CIPaused {
146 if s.Log != nil {
147 s.Log.Info("ci paused", "repo", repo.FullPath())
148 }
149 return 0
150 }
145 151 title, jobs, broken := s.planPipeline(ctx, repo, sha, ref, source, before, mr)
146 152 mrID, target := int64(0), ""
147 153 if mr != nil {
@@ -142,6 +142,12 @@ func (s *Server) startPipeline(ctx context.Context, repo store.Repo, sha, ref, a
142 if !s.Cfg.CI.Enabled || s.StoragePath() == "" {
142 if !s.Cfg.CI.Enabled || s.StoragePath() == "" {
143 return 0
143 return 0
144 }
144 }
145 if repo.CIPaused {
146 if s.Log != nil {
147 s.Log.Info("ci paused", "repo", repo.FullPath())
148 }
149 return 0
150 }
145 title, jobs, broken := s.planPipeline(ctx, repo, sha, ref, source, before, mr)
151 title, jobs, broken := s.planPipeline(ctx, repo, sha, ref, source, before, mr)
146 mrID, target := int64(0), ""
152 mrID, target := int64(0), ""
147 if mr != nil {
153 if mr != nil {
internal/server/kvt_feedback_test.go added +332 −0
@@ -0,0 +1,332 @@
1 package server
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "image"
9 "image/color"
10 "image/png"
11 "io"
12 "net/http"
13 "net/http/cookiejar"
14 "net/http/httptest"
15 "net/url"
16 "os"
17 "os/exec"
18 "path/filepath"
19 "strconv"
20 "strings"
21 "testing"
22
23 "gitlab.com/Timfa/bluegit/internal/auth"
24 "gitlab.com/Timfa/bluegit/internal/config"
25 "gitlab.com/Timfa/bluegit/internal/gitrepo"
26 "gitlab.com/Timfa/bluegit/internal/runner"
27 "gitlab.com/Timfa/bluegit/internal/store"
28 )
29
30 func TestPutProjectDefaultBranch(t *testing.T) {
31 if _, err := exec.LookPath("git"); err != nil {
32 t.Skip("git ontbreekt")
33 }
34 ts, client, srv := graphTestRepo(t)
35 tok := apiToken(t, client, ts.URL)
36 code, b := rapi(t, ts.URL, tok, "PUT", "/projects/tim/grafiek", map[string]any{"default_branch": "feature"})
37 if code != 200 {
38 t.Fatalf("PUT %d %s", code, b)
39 }
40 var out map[string]any
41 if err := json.Unmarshal(b, &out); err != nil {
42 t.Fatal(err)
43 }
44 if out["default_branch"] != "feature" {
45 t.Fatalf("antwoord: %s", b)
46 }
47 repo, err := srv.Store.RepoByPath(context.Background(), "tim", "grafiek")
48 if err != nil || repo.DefaultBranch != "feature" {
49 t.Fatalf("db: %+v %v", repo, err)
50 }
51 dir := gitrepo.Dir(srv.StoragePath(), "tim", "grafiek")
52 head, err := exec.Command("git", "-C", dir, "symbolic-ref", "--short", "HEAD").Output()
53 if err != nil || strings.TrimSpace(string(head)) != "feature" {
54 t.Fatalf("HEAD %q %v", head, err)
55 }
56 code, b = rapi(t, ts.URL, tok, "PUT", "/projects/tim/grafiek", map[string]any{"default_branch": "bestaat-niet"})
57 if code != 400 {
58 t.Fatalf("ontbrekende branch: %d %s", code, b)
59 }
60 }
61
62 func TestProjectCIPaused(t *testing.T) {
63 if _, err := exec.LookPath("git"); err != nil {
64 t.Skip("git ontbreekt")
65 }
66 ts, client, srv := graphTestRepo(t)
67 srv.Cfg.CI.Enabled = true
68 tok := apiToken(t, client, ts.URL)
69 code, b := rapi(t, ts.URL, tok, "PUT", "/projects/tim/grafiek", map[string]any{"ci_paused": true})
70 if code != 200 || !strings.Contains(string(b), `"ci_paused":true`) {
71 t.Fatalf("pause %d %s", code, b)
72 }
73 repo, _ := srv.Store.RepoByPath(context.Background(), "tim", "grafiek")
74 if !repo.CIPaused {
75 t.Fatal("db niet gepauzeerd")
76 }
77 settings := read(t, mustGet(t, client, ts.URL+"/tim/grafiek/-/settings"))
78 if !strings.Contains(settings, `name="ci_paused"`) || !strings.Contains(settings, "checked") {
79 t.Fatalf("settings-ui mist checkbox:\n%s", settings)
80 }
81 tim, err := srv.Store.UserByUsername(context.Background(), "tim")
82 if err != nil {
83 t.Fatal(err)
84 }
85 if _, err := srv.opRunPipeline(context.Background(), tim, repo, "master", "api"); err == nil {
86 t.Fatal("handmatige run had geweigerd moeten worden")
87 }
88 if got := srv.startPipeline(context.Background(), repo, strings.Repeat("a", 40), "refs/heads/master", "tim", "push", "", nil); got != 0 {
89 t.Fatalf("push zou geen pipeline moeten queueen: %d", got)
90 }
91 code, b = rapi(t, ts.URL, tok, "POST", "/projects/tim/grafiek/pipelines", map[string]any{"ref": "master"})
92 if code != 409 {
93 t.Fatalf("API start %d %s", code, b)
94 }
95 }
96
97 func TestAdminRunnerStatusDockerUnreachable(t *testing.T) {
98 dir := t.TempDir()
99 bin := filepath.Join(dir, "docker")
100 script := "#!/bin/sh\necho 'Cannot connect to the Docker daemon' >&2\nexit 1\n"
101 if err := os.WriteFile(bin, []byte(script), 0o755); err != nil {
102 t.Fatal(err)
103 }
104 srv := &Server{
105 Cfg: config.Config{BaseURL: "http://git.example", CI: config.CI{Docker: bin}},
106 Runner: &runner.Runner{},
107 }
108 st := srv.builtinStatus()
109 if st.Online {
110 t.Fatalf("online zou false moeten zijn: %+v", st)
111 }
112 if st.Docker.Reachable || st.Docker.Error == "" {
113 t.Fatalf("docker status: %+v", st.Docker)
114 }
115 }
116
117 func TestRepoLogoICO(t *testing.T) {
118 if _, err := exec.LookPath("git"); err != nil {
119 t.Skip("git ontbreekt")
120 }
121 ts, client, srv := graphTestRepo(t)
122 srv.StateDir = t.TempDir()
123 page := read(t, mustGet(t, client, ts.URL+"/tim/grafiek/-/settings"))
124 body, ctype := multipartLogo(t, csrfOf(t, page), encodeICOFile(solidPNG(16, 16)), "logo.ico")
125 req, err := http.NewRequest(http.MethodPost, ts.URL+"/tim/grafiek/-/logo", body)
126 if err != nil {
127 t.Fatal(err)
128 }
129 req.Header.Set("Content-Type", ctype)
130 res, err := client.Do(req)
131 if err != nil {
132 t.Fatal(err)
133 }
134 _ = read(t, res)
135 repo, err := srv.Store.RepoByPath(context.Background(), "tim", "grafiek")
136 if err != nil || repo.LogoMIME != "image/x-icon" {
137 t.Fatalf("mime %q %v", repo.LogoMIME, err)
138 }
139 res, err = client.Get(ts.URL + "/tim/grafiek/-/logo")
140 if err != nil {
141 t.Fatal(err)
142 }
143 defer res.Body.Close()
144 if res.StatusCode != 200 || res.Header.Get("Content-Type") != "image/x-icon" {
145 t.Fatalf("serve %d %s", res.StatusCode, res.Header.Get("Content-Type"))
146 }
147 }
148
149 func TestJobHeaderUserchipWithoutAvatar(t *testing.T) {
150 css, err := os.ReadFile("static/style.css")
151 if err != nil {
152 t.Fatal(err)
153 }
154 if !strings.Contains(string(css), ".userchip, a.userchip-link") || !strings.Contains(string(css), "inline-flex") {
155 t.Fatal("userchip-css ontbreekt")
156 }
157 storage := t.TempDir()
158 st, err := store.Open(filepath.Join(storage, "bluegit.db"), bytes32())
159 if err != nil {
160 t.Fatal(err)
161 }
162 t.Cleanup(func() { _ = st.Close() })
163 cfg := config.Config{
164 BaseURL: "http://127.0.0.1:9", Listen: "127.0.0.1:0", StoragePath: storage,
165 Auth: config.Auth{Mode: "dev", DevUser: "tim", DevAuthID: 1, UserAgent: "test", BaseURL: "https://auth.timfalken.com"},
166 Git: config.Git{Binary: "git", DefaultBranch: "master"},
167 }
168 srv := &Server{Cfg: cfg, Store: st, Auth: auth.Dev{Username: "tim", AuthID: 1}, Dev: true, Git: "git"}
169 ts := httptest.NewServer(srv.Handler())
170 t.Cleanup(ts.Close)
171 jar, _ := cookiejar.New(nil)
172 client := &http.Client{Jar: jar}
173 _ = read(t, mustGet(t, client, ts.URL+"/login"))
174 ctx := context.Background()
175 user, err := st.UserByUsername(ctx, "tim")
176 if err != nil {
177 t.Fatal(err)
178 }
179 if user.AvatarURL != "" {
180 t.Fatal("verwacht geen avatar")
181 }
182 repo, err := st.CreateRepo(ctx, "user", user.ID, "demo", "", "master", "private")
183 if err != nil {
184 t.Fatal(err)
185 }
186 pid, err := st.CreatePipeline(ctx, repo.ID, strings.Repeat("a", 40), "refs/heads/master", "push", "tim", "run", []store.NewJob{
187 {Name: "build", Stage: "test", Script: "true"},
188 })
189 if err != nil {
190 t.Fatal(err)
191 }
192 jobs, _ := st.JobsByPipeline(ctx, pid)
193 if err := st.FinishJob(ctx, jobs[0].ID, "success", ""); err != nil {
194 t.Fatal(err)
195 }
196 page := read(t, mustGet(t, client, ts.URL+"/tim/demo/-/pipelines/"+strconv.FormatInt(pid, 10)+"/jobs/"+strconv.FormatInt(jobs[0].ID, 10)))
197 if !strings.Contains(page, `class="userchip"`) || !strings.Contains(page, `class="userchip-name"`) {
198 t.Fatalf("userchip ontbreekt:\n%s", page)
199 }
200 if !strings.Contains(page, ">tim<") {
201 t.Fatalf("naam ontbreekt:\n%s", page)
202 }
203 if strings.Contains(page, `class="avatarlink"`) {
204 t.Fatalf("naam mag niet in avatarlink:\n%s", page)
205 }
206 if !strings.Contains(page, tileHue("tim")) {
207 t.Fatalf("initialen-fallback zonder kleur:\n%s", page)
208 }
209 if strings.Contains(page, `<img class="avatar sm"`) {
210 t.Fatal("geen img voor gebruiker zonder avatar")
211 }
212 if os.Getenv("JOBCHIP_HOLD") != "" {
213 jobURL := ts.URL + "/tim/demo/-/pipelines/" + strconv.FormatInt(pid, 10) + "/jobs/" + strconv.FormatInt(jobs[0].ID, 10)
214 fmt.Fprintln(os.Stderr, "JOBCHIP_URL="+jobURL)
215 for _, c := range client.Jar.Cookies(mustParse(t, ts.URL)) {
216 fmt.Fprintf(os.Stderr, "JOBCHIP_COOKIE=%s=%s\n", c.Name, c.Value)
217 }
218 fmt.Fprintln(os.Stderr, "JOBCHIP_READY")
219 select {}
220 }
221 }
222
223 func TestStoreUserAvatarSkipsManual(t *testing.T) {
224 st, err := store.Open(filepath.Join(t.TempDir(), "bluegit.db"), bytes32())
225 if err != nil {
226 t.Fatal(err)
227 }
228 t.Cleanup(func() { _ = st.Close() })
229 ctx := context.Background()
230 u, err := st.UpsertUser(ctx, 9, "ada", "", false)
231 if err != nil {
232 t.Fatal(err)
233 }
234 if err := st.SetUserAvatar(ctx, u.ID, "/users/ada/avatar", "upload", "image/png"); err != nil {
235 t.Fatal(err)
236 }
237 if _, err := st.UpsertUser(ctx, 9, "ada", "https://example/photo.png", false); err != nil {
238 t.Fatal(err)
239 }
240 got, err := st.UserByID(ctx, u.ID)
241 if err != nil {
242 t.Fatal(err)
243 }
244 if got.AvatarURL != "/users/ada/avatar" || got.AvatarSource != "upload" {
245 t.Fatalf("handmatige avatar overschreven: %+v", got)
246 }
247 }
248
249 func TestStoreUserAvatarEntraRefresh(t *testing.T) {
250 stateDir := t.TempDir()
251 st, err := store.Open(filepath.Join(stateDir, "bluegit.db"), bytes32())
252 if err != nil {
253 t.Fatal(err)
254 }
255 t.Cleanup(func() { _ = st.Close() })
256 ctx := context.Background()
257 u, err := st.UpsertUser(ctx, 11, "ada", "", false)
258 if err != nil {
259 t.Fatal(err)
260 }
261 srv := &Server{Cfg: config.Config{BaseURL: "http://127.0.0.1:9", Listen: "127.0.0.1:0"}, Store: st, StateDir: stateDir}
262 if err := srv.storeUserAvatar(ctx, u, solidPNG(8, 8), "entra"); err != nil {
263 t.Fatal(err)
264 }
265 got, err := st.UserByID(ctx, u.ID)
266 if err != nil || got.AvatarSource != "entra" || got.AvatarURL != "/users/ada/avatar" {
267 t.Fatalf("opslag: %+v %v", got, err)
268 }
269 ts := httptest.NewServer(srv.Handler())
270 t.Cleanup(ts.Close)
271 res, err := http.Get(ts.URL + "/users/ada/avatar")
272 if err != nil {
273 t.Fatal(err)
274 }
275 defer res.Body.Close()
276 body, _ := io.ReadAll(res.Body)
277 if res.StatusCode != 200 || res.Header.Get("Content-Type") != "image/png" || len(body) == 0 {
278 t.Fatalf("serve %d %s %d", res.StatusCode, res.Header.Get("Content-Type"), len(body))
279 }
280 if err := st.SetUserAvatar(ctx, u.ID, got.AvatarURL, "upload", got.AvatarMIME); err != nil {
281 t.Fatal(err)
282 }
283 fresh, _ := st.UserByID(ctx, u.ID)
284 if err := srv.storeUserAvatar(ctx, fresh, solidPNG(4, 4), "entra"); err != nil {
285 t.Fatal(err)
286 }
287 again, _ := st.UserByID(ctx, u.ID)
288 if again.AvatarSource != "upload" {
289 t.Fatalf("entra overschreef upload: %+v", again)
290 }
291 }
292
293 func apiToken(t *testing.T, client *http.Client, base string) string {
294 t.Helper()
295 page := read(t, mustGet(t, client, base+"/settings"))
296 page = read(t, mustPost(t, client, base+"/settings/tokens", url.Values{"csrf": {csrfOf(t, page)}, "name": {"api"}}))
297 tok := between(page, `<p class="code">`, "</p>")
298 if tok == "" {
299 t.Fatal("geen token")
300 }
301 return tok
302 }
303
304 func solidPNG(w, h int) []byte {
305 img := image.NewNRGBA(image.Rect(0, 0, w, h))
306 for y := 0; y < h; y++ {
307 for x := 0; x < w; x++ {
308 img.SetNRGBA(x, y, color.NRGBA{R: 31, G: 111, B: 235, A: 255})
309 }
310 }
311 var buf bytes.Buffer
312 _ = png.Encode(&buf, img)
313 return buf.Bytes()
314 }
315
316 func encodeICOFile(png []byte) []byte {
317 buf := make([]byte, 6+16+len(png))
318 buf[2] = 1
319 buf[4] = 1
320 buf[6] = 16
321 buf[7] = 16
322 n := uint32(len(png))
323 buf[14] = byte(n)
324 buf[15] = byte(n >> 8)
325 buf[16] = byte(n >> 16)
326 buf[17] = byte(n >> 24)
327 off := uint32(22)
328 buf[18] = byte(off)
329 buf[19] = byte(off >> 8)
330 copy(buf[22:], png)
331 return buf
332 }
@@ -0,0 +1,332 @@
1package server
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "image"
9 "image/color"
10 "image/png"
11 "io"
12 "net/http"
13 "net/http/cookiejar"
14 "net/http/httptest"
15 "net/url"
16 "os"
17 "os/exec"
18 "path/filepath"
19 "strconv"
20 "strings"
21 "testing"
22
23 "gitlab.com/Timfa/bluegit/internal/auth"
24 "gitlab.com/Timfa/bluegit/internal/config"
25 "gitlab.com/Timfa/bluegit/internal/gitrepo"
26 "gitlab.com/Timfa/bluegit/internal/runner"
27 "gitlab.com/Timfa/bluegit/internal/store"
28)
29
30func TestPutProjectDefaultBranch(t *testing.T) {
31 if _, err := exec.LookPath("git"); err != nil {
32 t.Skip("git ontbreekt")
33 }
34 ts, client, srv := graphTestRepo(t)
35 tok := apiToken(t, client, ts.URL)
36 code, b := rapi(t, ts.URL, tok, "PUT", "/projects/tim/grafiek", map[string]any{"default_branch": "feature"})
37 if code != 200 {
38 t.Fatalf("PUT %d %s", code, b)
39 }
40 var out map[string]any
41 if err := json.Unmarshal(b, &out); err != nil {
42 t.Fatal(err)
43 }
44 if out["default_branch"] != "feature" {
45 t.Fatalf("antwoord: %s", b)
46 }
47 repo, err := srv.Store.RepoByPath(context.Background(), "tim", "grafiek")
48 if err != nil || repo.DefaultBranch != "feature" {
49 t.Fatalf("db: %+v %v", repo, err)
50 }
51 dir := gitrepo.Dir(srv.StoragePath(), "tim", "grafiek")
52 head, err := exec.Command("git", "-C", dir, "symbolic-ref", "--short", "HEAD").Output()
53 if err != nil || strings.TrimSpace(string(head)) != "feature" {
54 t.Fatalf("HEAD %q %v", head, err)
55 }
56 code, b = rapi(t, ts.URL, tok, "PUT", "/projects/tim/grafiek", map[string]any{"default_branch": "bestaat-niet"})
57 if code != 400 {
58 t.Fatalf("ontbrekende branch: %d %s", code, b)
59 }
60}
61
62func TestProjectCIPaused(t *testing.T) {
63 if _, err := exec.LookPath("git"); err != nil {
64 t.Skip("git ontbreekt")
65 }
66 ts, client, srv := graphTestRepo(t)
67 srv.Cfg.CI.Enabled = true
68 tok := apiToken(t, client, ts.URL)
69 code, b := rapi(t, ts.URL, tok, "PUT", "/projects/tim/grafiek", map[string]any{"ci_paused": true})
70 if code != 200 || !strings.Contains(string(b), `"ci_paused":true`) {
71 t.Fatalf("pause %d %s", code, b)
72 }
73 repo, _ := srv.Store.RepoByPath(context.Background(), "tim", "grafiek")
74 if !repo.CIPaused {
75 t.Fatal("db niet gepauzeerd")
76 }
77 settings := read(t, mustGet(t, client, ts.URL+"/tim/grafiek/-/settings"))
78 if !strings.Contains(settings, `name="ci_paused"`) || !strings.Contains(settings, "checked") {
79 t.Fatalf("settings-ui mist checkbox:\n%s", settings)
80 }
81 tim, err := srv.Store.UserByUsername(context.Background(), "tim")
82 if err != nil {
83 t.Fatal(err)
84 }
85 if _, err := srv.opRunPipeline(context.Background(), tim, repo, "master", "api"); err == nil {
86 t.Fatal("handmatige run had geweigerd moeten worden")
87 }
88 if got := srv.startPipeline(context.Background(), repo, strings.Repeat("a", 40), "refs/heads/master", "tim", "push", "", nil); got != 0 {
89 t.Fatalf("push zou geen pipeline moeten queueen: %d", got)
90 }
91 code, b = rapi(t, ts.URL, tok, "POST", "/projects/tim/grafiek/pipelines", map[string]any{"ref": "master"})
92 if code != 409 {
93 t.Fatalf("API start %d %s", code, b)
94 }
95}
96
97func TestAdminRunnerStatusDockerUnreachable(t *testing.T) {
98 dir := t.TempDir()
99 bin := filepath.Join(dir, "docker")
100 script := "#!/bin/sh\necho 'Cannot connect to the Docker daemon' >&2\nexit 1\n"
101 if err := os.WriteFile(bin, []byte(script), 0o755); err != nil {
102 t.Fatal(err)
103 }
104 srv := &Server{
105 Cfg: config.Config{BaseURL: "http://git.example", CI: config.CI{Docker: bin}},
106 Runner: &runner.Runner{},
107 }
108 st := srv.builtinStatus()
109 if st.Online {
110 t.Fatalf("online zou false moeten zijn: %+v", st)
111 }
112 if st.Docker.Reachable || st.Docker.Error == "" {
113 t.Fatalf("docker status: %+v", st.Docker)
114 }
115}
116
117func TestRepoLogoICO(t *testing.T) {
118 if _, err := exec.LookPath("git"); err != nil {
119 t.Skip("git ontbreekt")
120 }
121 ts, client, srv := graphTestRepo(t)
122 srv.StateDir = t.TempDir()
123 page := read(t, mustGet(t, client, ts.URL+"/tim/grafiek/-/settings"))
124 body, ctype := multipartLogo(t, csrfOf(t, page), encodeICOFile(solidPNG(16, 16)), "logo.ico")
125 req, err := http.NewRequest(http.MethodPost, ts.URL+"/tim/grafiek/-/logo", body)
126 if err != nil {
127 t.Fatal(err)
128 }
129 req.Header.Set("Content-Type", ctype)
130 res, err := client.Do(req)
131 if err != nil {
132 t.Fatal(err)
133 }
134 _ = read(t, res)
135 repo, err := srv.Store.RepoByPath(context.Background(), "tim", "grafiek")
136 if err != nil || repo.LogoMIME != "image/x-icon" {
137 t.Fatalf("mime %q %v", repo.LogoMIME, err)
138 }
139 res, err = client.Get(ts.URL + "/tim/grafiek/-/logo")
140 if err != nil {
141 t.Fatal(err)
142 }
143 defer res.Body.Close()
144 if res.StatusCode != 200 || res.Header.Get("Content-Type") != "image/x-icon" {
145 t.Fatalf("serve %d %s", res.StatusCode, res.Header.Get("Content-Type"))
146 }
147}
148
149func TestJobHeaderUserchipWithoutAvatar(t *testing.T) {
150 css, err := os.ReadFile("static/style.css")
151 if err != nil {
152 t.Fatal(err)
153 }
154 if !strings.Contains(string(css), ".userchip, a.userchip-link") || !strings.Contains(string(css), "inline-flex") {
155 t.Fatal("userchip-css ontbreekt")
156 }
157 storage := t.TempDir()
158 st, err := store.Open(filepath.Join(storage, "bluegit.db"), bytes32())
159 if err != nil {
160 t.Fatal(err)
161 }
162 t.Cleanup(func() { _ = st.Close() })
163 cfg := config.Config{
164 BaseURL: "http://127.0.0.1:9", Listen: "127.0.0.1:0", StoragePath: storage,
165 Auth: config.Auth{Mode: "dev", DevUser: "tim", DevAuthID: 1, UserAgent: "test", BaseURL: "https://auth.timfalken.com"},
166 Git: config.Git{Binary: "git", DefaultBranch: "master"},
167 }
168 srv := &Server{Cfg: cfg, Store: st, Auth: auth.Dev{Username: "tim", AuthID: 1}, Dev: true, Git: "git"}
169 ts := httptest.NewServer(srv.Handler())
170 t.Cleanup(ts.Close)
171 jar, _ := cookiejar.New(nil)
172 client := &http.Client{Jar: jar}
173 _ = read(t, mustGet(t, client, ts.URL+"/login"))
174 ctx := context.Background()
175 user, err := st.UserByUsername(ctx, "tim")
176 if err != nil {
177 t.Fatal(err)
178 }
179 if user.AvatarURL != "" {
180 t.Fatal("verwacht geen avatar")
181 }
182 repo, err := st.CreateRepo(ctx, "user", user.ID, "demo", "", "master", "private")
183 if err != nil {
184 t.Fatal(err)
185 }
186 pid, err := st.CreatePipeline(ctx, repo.ID, strings.Repeat("a", 40), "refs/heads/master", "push", "tim", "run", []store.NewJob{
187 {Name: "build", Stage: "test", Script: "true"},
188 })
189 if err != nil {
190 t.Fatal(err)
191 }
192 jobs, _ := st.JobsByPipeline(ctx, pid)
193 if err := st.FinishJob(ctx, jobs[0].ID, "success", ""); err != nil {
194 t.Fatal(err)
195 }
196 page := read(t, mustGet(t, client, ts.URL+"/tim/demo/-/pipelines/"+strconv.FormatInt(pid, 10)+"/jobs/"+strconv.FormatInt(jobs[0].ID, 10)))
197 if !strings.Contains(page, `class="userchip"`) || !strings.Contains(page, `class="userchip-name"`) {
198 t.Fatalf("userchip ontbreekt:\n%s", page)
199 }
200 if !strings.Contains(page, ">tim<") {
201 t.Fatalf("naam ontbreekt:\n%s", page)
202 }
203 if strings.Contains(page, `class="avatarlink"`) {
204 t.Fatalf("naam mag niet in avatarlink:\n%s", page)
205 }
206 if !strings.Contains(page, tileHue("tim")) {
207 t.Fatalf("initialen-fallback zonder kleur:\n%s", page)
208 }
209 if strings.Contains(page, `<img class="avatar sm"`) {
210 t.Fatal("geen img voor gebruiker zonder avatar")
211 }
212 if os.Getenv("JOBCHIP_HOLD") != "" {
213 jobURL := ts.URL + "/tim/demo/-/pipelines/" + strconv.FormatInt(pid, 10) + "/jobs/" + strconv.FormatInt(jobs[0].ID, 10)
214 fmt.Fprintln(os.Stderr, "JOBCHIP_URL="+jobURL)
215 for _, c := range client.Jar.Cookies(mustParse(t, ts.URL)) {
216 fmt.Fprintf(os.Stderr, "JOBCHIP_COOKIE=%s=%s\n", c.Name, c.Value)
217 }
218 fmt.Fprintln(os.Stderr, "JOBCHIP_READY")
219 select {}
220 }
221}
222
223func TestStoreUserAvatarSkipsManual(t *testing.T) {
224 st, err := store.Open(filepath.Join(t.TempDir(), "bluegit.db"), bytes32())
225 if err != nil {
226 t.Fatal(err)
227 }
228 t.Cleanup(func() { _ = st.Close() })
229 ctx := context.Background()
230 u, err := st.UpsertUser(ctx, 9, "ada", "", false)
231 if err != nil {
232 t.Fatal(err)
233 }
234 if err := st.SetUserAvatar(ctx, u.ID, "/users/ada/avatar", "upload", "image/png"); err != nil {
235 t.Fatal(err)
236 }
237 if _, err := st.UpsertUser(ctx, 9, "ada", "https://example/photo.png", false); err != nil {
238 t.Fatal(err)
239 }
240 got, err := st.UserByID(ctx, u.ID)
241 if err != nil {
242 t.Fatal(err)
243 }
244 if got.AvatarURL != "/users/ada/avatar" || got.AvatarSource != "upload" {
245 t.Fatalf("handmatige avatar overschreven: %+v", got)
246 }
247}
248
249func TestStoreUserAvatarEntraRefresh(t *testing.T) {
250 stateDir := t.TempDir()
251 st, err := store.Open(filepath.Join(stateDir, "bluegit.db"), bytes32())
252 if err != nil {
253 t.Fatal(err)
254 }
255 t.Cleanup(func() { _ = st.Close() })
256 ctx := context.Background()
257 u, err := st.UpsertUser(ctx, 11, "ada", "", false)
258 if err != nil {
259 t.Fatal(err)
260 }
261 srv := &Server{Cfg: config.Config{BaseURL: "http://127.0.0.1:9", Listen: "127.0.0.1:0"}, Store: st, StateDir: stateDir}
262 if err := srv.storeUserAvatar(ctx, u, solidPNG(8, 8), "entra"); err != nil {
263 t.Fatal(err)
264 }
265 got, err := st.UserByID(ctx, u.ID)
266 if err != nil || got.AvatarSource != "entra" || got.AvatarURL != "/users/ada/avatar" {
267 t.Fatalf("opslag: %+v %v", got, err)
268 }
269 ts := httptest.NewServer(srv.Handler())
270 t.Cleanup(ts.Close)
271 res, err := http.Get(ts.URL + "/users/ada/avatar")
272 if err != nil {
273 t.Fatal(err)
274 }
275 defer res.Body.Close()
276 body, _ := io.ReadAll(res.Body)
277 if res.StatusCode != 200 || res.Header.Get("Content-Type") != "image/png" || len(body) == 0 {
278 t.Fatalf("serve %d %s %d", res.StatusCode, res.Header.Get("Content-Type"), len(body))
279 }
280 if err := st.SetUserAvatar(ctx, u.ID, got.AvatarURL, "upload", got.AvatarMIME); err != nil {
281 t.Fatal(err)
282 }
283 fresh, _ := st.UserByID(ctx, u.ID)
284 if err := srv.storeUserAvatar(ctx, fresh, solidPNG(4, 4), "entra"); err != nil {
285 t.Fatal(err)
286 }
287 again, _ := st.UserByID(ctx, u.ID)
288 if again.AvatarSource != "upload" {
289 t.Fatalf("entra overschreef upload: %+v", again)
290 }
291}
292
293func apiToken(t *testing.T, client *http.Client, base string) string {
294 t.Helper()
295 page := read(t, mustGet(t, client, base+"/settings"))
296 page = read(t, mustPost(t, client, base+"/settings/tokens", url.Values{"csrf": {csrfOf(t, page)}, "name": {"api"}}))
297 tok := between(page, `<p class="code">`, "</p>")
298 if tok == "" {
299 t.Fatal("geen token")
300 }
301 return tok
302}
303
304func solidPNG(w, h int) []byte {
305 img := image.NewNRGBA(image.Rect(0, 0, w, h))
306 for y := 0; y < h; y++ {
307 for x := 0; x < w; x++ {
308 img.SetNRGBA(x, y, color.NRGBA{R: 31, G: 111, B: 235, A: 255})
309 }
310 }
311 var buf bytes.Buffer
312 _ = png.Encode(&buf, img)
313 return buf.Bytes()
314}
315
316func encodeICOFile(png []byte) []byte {
317 buf := make([]byte, 6+16+len(png))
318 buf[2] = 1
319 buf[4] = 1
320 buf[6] = 16
321 buf[7] = 16
322 n := uint32(len(png))
323 buf[14] = byte(n)
324 buf[15] = byte(n >> 8)
325 buf[16] = byte(n >> 16)
326 buf[17] = byte(n >> 24)
327 off := uint32(22)
328 buf[18] = byte(off)
329 buf[19] = byte(off >> 8)
330 copy(buf[22:], png)
331 return buf
332}
internal/server/mr_layout_test.go +1 −1
@@ -78,7 +78,7 @@ func TestMRPageLayout(t *testing.T) {
78 78 `Changes <span class="count">2</span>`,
79 79 `Pipelines <span class="count">0</span>`,
80 80 "Delete source branch", "> Squash",
81 "created just now", `href="/users/tim"`, `class="avatar sm">T</span>`,
81 "created just now", `href="/users/tim"`, `class="userchip"`,
82 82 "mrwidget",
83 83 } {
84 84 if !strings.Contains(page, want) {
@@ -78,7 +78,7 @@ func TestMRPageLayout(t *testing.T) {
78 `Changes <span class="count">2</span>`,
78 `Changes <span class="count">2</span>`,
79 `Pipelines <span class="count">0</span>`,
79 `Pipelines <span class="count">0</span>`,
80 "Delete source branch", "> Squash",
80 "Delete source branch", "> Squash",
81 "created just now", `href="/users/tim"`, `class="avatar sm">T</span>`,
81 "created just now", `href="/users/tim"`, `class="userchip"`,
82 "mrwidget",
82 "mrwidget",
83 } {
83 } {
84 if !strings.Contains(page, want) {
84 if !strings.Contains(page, want) {
internal/server/ops_ci.go +3 −0
@@ -23,6 +23,9 @@ func (s *Server) opRunPipeline(ctx context.Context, user store.User, repo store.
23 23 if !role.CanWriteCode() {
24 24 return 0, fail(403, i18n.E("err.forbidden"))
25 25 }
26 if repo.CIPaused {
27 return 0, fail(409, i18n.E("err.ciPaused"))
28 }
26 29 ref = safeRev(ref, repo.DefaultBranch)
27 30 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
28 31 sha := gitOne(ctx, s.Git, dir, "rev-parse", "--verify", ref+"^{commit}")
@@ -23,6 +23,9 @@ func (s *Server) opRunPipeline(ctx context.Context, user store.User, repo store.
23 if !role.CanWriteCode() {
23 if !role.CanWriteCode() {
24 return 0, fail(403, i18n.E("err.forbidden"))
24 return 0, fail(403, i18n.E("err.forbidden"))
25 }
25 }
26 if repo.CIPaused {
27 return 0, fail(409, i18n.E("err.ciPaused"))
28 }
26 ref = safeRev(ref, repo.DefaultBranch)
29 ref = safeRev(ref, repo.DefaultBranch)
27 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
30 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
28 sha := gitOne(ctx, s.Git, dir, "rev-parse", "--verify", ref+"^{commit}")
31 sha := gitOne(ctx, s.Git, dir, "rev-parse", "--verify", ref+"^{commit}")
internal/server/ops_collab.go +32 −0
@@ -148,6 +148,38 @@ func (s *Server) opUpdateRepo(ctx context.Context, user store.User, repo store.R
148 148 return nil
149 149 }
150 150
151 // opSetDefaultBranch zet HEAD en de metadata naar een bestaande branch.
152 func (s *Server) opSetDefaultBranch(ctx context.Context, user store.User, repo store.Repo, branch string) error {
153 role, err := s.Store.EffectiveRole(ctx, user.ID, repo.ID)
154 if err != nil || !role.CanManageSettings() {
155 return fail(403, i18n.E("err.forbidden"))
156 }
157 branch = strings.TrimSpace(branch)
158 if err := names.ValidBranch(branch); err != nil {
159 return fail(400, err)
160 }
161 if branch == repo.DefaultBranch {
162 return nil
163 }
164 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
165 if !gitrepo.HasBranch(ctx, s.Git, dir, branch) {
166 return fail(400, i18n.E("err.branchMissing"))
167 }
168 if err := gitrepo.SetHEAD(ctx, s.Git, dir, branch); err != nil {
169 return err
170 }
171 return s.Store.SetDefaultBranch(ctx, repo.ID, branch)
172 }
173
174 // opSetRepoCIPaused zet of nieuwe pipelines mogen worden ingepland.
175 func (s *Server) opSetRepoCIPaused(ctx context.Context, user store.User, repo store.Repo, paused bool) error {
176 role, err := s.Store.EffectiveRole(ctx, user.ID, repo.ID)
177 if err != nil || !role.CanManageSettings() {
178 return fail(403, i18n.E("err.forbidden"))
179 }
180 return s.Store.SetRepoCIPaused(ctx, repo.ID, paused)
181 }
182
151 183 // opSetReleaseVisibility zet inherit, private of public (alleen beheerders).
152 184 func (s *Server) opSetReleaseVisibility(ctx context.Context, user store.User, repo store.Repo, v string) error {
153 185 role, err := s.Store.EffectiveRole(ctx, user.ID, repo.ID)
@@ -148,6 +148,38 @@ func (s *Server) opUpdateRepo(ctx context.Context, user store.User, repo store.R
148 return nil
148 return nil
149}
149}
150
150
151// opSetDefaultBranch zet HEAD en de metadata naar een bestaande branch.
152func (s *Server) opSetDefaultBranch(ctx context.Context, user store.User, repo store.Repo, branch string) error {
153 role, err := s.Store.EffectiveRole(ctx, user.ID, repo.ID)
154 if err != nil || !role.CanManageSettings() {
155 return fail(403, i18n.E("err.forbidden"))
156 }
157 branch = strings.TrimSpace(branch)
158 if err := names.ValidBranch(branch); err != nil {
159 return fail(400, err)
160 }
161 if branch == repo.DefaultBranch {
162 return nil
163 }
164 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
165 if !gitrepo.HasBranch(ctx, s.Git, dir, branch) {
166 return fail(400, i18n.E("err.branchMissing"))
167 }
168 if err := gitrepo.SetHEAD(ctx, s.Git, dir, branch); err != nil {
169 return err
170 }
171 return s.Store.SetDefaultBranch(ctx, repo.ID, branch)
172}
173
174// opSetRepoCIPaused zet of nieuwe pipelines mogen worden ingepland.
175func (s *Server) opSetRepoCIPaused(ctx context.Context, user store.User, repo store.Repo, paused bool) error {
176 role, err := s.Store.EffectiveRole(ctx, user.ID, repo.ID)
177 if err != nil || !role.CanManageSettings() {
178 return fail(403, i18n.E("err.forbidden"))
179 }
180 return s.Store.SetRepoCIPaused(ctx, repo.ID, paused)
181}
182
151// opSetReleaseVisibility zet inherit, private of public (alleen beheerders).
183// opSetReleaseVisibility zet inherit, private of public (alleen beheerders).
152func (s *Server) opSetReleaseVisibility(ctx context.Context, user store.User, repo store.Repo, v string) error {
184func (s *Server) opSetReleaseVisibility(ctx context.Context, user store.User, repo store.Repo, v string) error {
153 role, err := s.Store.EffectiveRole(ctx, user.ID, repo.ID)
185 role, err := s.Store.EffectiveRole(ctx, user.ID, repo.ID)
internal/server/server.go +1 −0
@@ -130,6 +130,7 @@ func (s *Server) Handler() http.Handler {
130 130 mux.HandleFunc("POST /settings/ssh/delete", s.deleteSSH)
131 131 mux.HandleFunc("GET /settings/export", s.export)
132 132 mux.HandleFunc("GET /users/{username}", s.profile)
133 mux.HandleFunc("GET /users/{username}/avatar", s.userAvatar)
133 134 mux.HandleFunc("GET /users/{username}/{$}", s.trimSlash)
134 135 mux.HandleFunc("GET /{name}", s.userShort)
135 136 mux.HandleFunc("GET /{name}/{$}", s.userShort)
@@ -130,6 +130,7 @@ func (s *Server) Handler() http.Handler {
130 mux.HandleFunc("POST /settings/ssh/delete", s.deleteSSH)
130 mux.HandleFunc("POST /settings/ssh/delete", s.deleteSSH)
131 mux.HandleFunc("GET /settings/export", s.export)
131 mux.HandleFunc("GET /settings/export", s.export)
132 mux.HandleFunc("GET /users/{username}", s.profile)
132 mux.HandleFunc("GET /users/{username}", s.profile)
133 mux.HandleFunc("GET /users/{username}/avatar", s.userAvatar)
133 mux.HandleFunc("GET /users/{username}/{$}", s.trimSlash)
134 mux.HandleFunc("GET /users/{username}/{$}", s.trimSlash)
134 mux.HandleFunc("GET /{name}", s.userShort)
135 mux.HandleFunc("GET /{name}", s.userShort)
135 mux.HandleFunc("GET /{name}/{$}", s.userShort)
136 mux.HandleFunc("GET /{name}/{$}", s.userShort)
internal/server/settings_handlers.go +4 −0
@@ -204,6 +204,10 @@ func (s *Server) updateRepo(w http.ResponseWriter, r *http.Request) {
204 204 return
205 205 }
206 206 }
207 if err := s.opSetRepoCIPaused(r.Context(), s.who(r).User, repo, r.FormValue("ci_paused") == "1"); err != nil {
208 s.redirect(w, r, repoURL(repo)+"/-/settings", "", s.commitProblem(r, err))
209 return
210 }
207 211 if sd := strings.TrimSpace(r.FormValue("stale_manual_days")); sd != "" || r.Form.Has("stale_manual_days") {
208 212 n := -1
209 213 if sd != "" {
@@ -204,6 +204,10 @@ func (s *Server) updateRepo(w http.ResponseWriter, r *http.Request) {
204 return
204 return
205 }
205 }
206 }
206 }
207 if err := s.opSetRepoCIPaused(r.Context(), s.who(r).User, repo, r.FormValue("ci_paused") == "1"); err != nil {
208 s.redirect(w, r, repoURL(repo)+"/-/settings", "", s.commitProblem(r, err))
209 return
210 }
207 if sd := strings.TrimSpace(r.FormValue("stale_manual_days")); sd != "" || r.Form.Has("stale_manual_days") {
211 if sd := strings.TrimSpace(r.FormValue("stale_manual_days")); sd != "" || r.Form.Has("stale_manual_days") {
208 n := -1
212 n := -1
209 if sd != "" {
213 if sd != "" {
internal/server/static/style.css +13 −0
@@ -366,6 +366,19 @@ a.status.markonly { padding: 0; background: transparent; min-height: 0; }
366 366 .avatar.xl { width: 96px; height: 96px; font-size: 2rem; }
367 367 a.avatarlink { display: inline-grid; color: inherit; text-decoration: none; line-height: 0; }
368 368 a.avatarlink:hover { text-decoration: none; }
369 .userchip, a.userchip-link {
370 display: inline-flex;
371 align-items: center;
372 gap: 0.35rem;
373 vertical-align: middle;
374 line-height: 1.2;
375 color: inherit;
376 text-decoration: none;
377 font-weight: 650;
378 }
379 a.userchip-link:hover { text-decoration: none; }
380 .userchip-name { line-height: 1.2; font-weight: 650; }
381 .userchip .avatar.sm { flex: none; }
369 382 .usercard {
370 383 display: grid; grid-template-columns: auto minmax(0, 1fr) auto;
371 384 gap: 1.1rem; align-items: start; margin: 0.4rem 0 1.1rem;
@@ -366,6 +366,19 @@ a.status.markonly { padding: 0; background: transparent; min-height: 0; }
366.avatar.xl { width: 96px; height: 96px; font-size: 2rem; }
366.avatar.xl { width: 96px; height: 96px; font-size: 2rem; }
367a.avatarlink { display: inline-grid; color: inherit; text-decoration: none; line-height: 0; }
367a.avatarlink { display: inline-grid; color: inherit; text-decoration: none; line-height: 0; }
368a.avatarlink:hover { text-decoration: none; }
368a.avatarlink:hover { text-decoration: none; }
369.userchip, a.userchip-link {
370 display: inline-flex;
371 align-items: center;
372 gap: 0.35rem;
373 vertical-align: middle;
374 line-height: 1.2;
375 color: inherit;
376 text-decoration: none;
377 font-weight: 650;
378}
379a.userchip-link:hover { text-decoration: none; }
380.userchip-name { line-height: 1.2; font-weight: 650; }
381.userchip .avatar.sm { flex: none; }
369.usercard {
382.usercard {
370 display: grid; grid-template-columns: auto minmax(0, 1fr) auto;
383 display: grid; grid-template-columns: auto minmax(0, 1fr) auto;
371 gap: 1.1rem; align-items: start; margin: 0.4rem 0 1.1rem;
384 gap: 1.1rem; align-items: start; margin: 0.4rem 0 1.1rem;
internal/server/templates/collab.html +6 −4
@@ -89,7 +89,7 @@
89 89 <p class="mrmeta">!{{.MR.Number}}{{if .Banner}} · {{.Banner.WhenLabel}}{{end}}</p>
90 90 {{if .Banner}}
91 91 <p class="mrwant">
92 {{if .Banner.AuthorURL}}<a class="who" href="{{.Banner.AuthorURL}}">{{if .Banner.Avatar}}<img class="avatar sm" src="{{.Banner.Avatar}}" alt="">{{else}}<span class="avatar sm">{{.Banner.Initial}}</span>{{end}}{{.Banner.Author}}</a>{{else if .Banner.Author}}<span class="avatar sm">{{.Banner.Initial}}</span> <strong>{{.Banner.Author}}</strong>{{end}}
92 {{if .Banner.Author}}<span class="userchip">{{if .Banner.AuthorURL}}<a class="userchip-link" href="{{.Banner.AuthorURL}}">{{end}}{{if .Banner.Avatar}}<img class="avatar sm" src="{{.Banner.Avatar}}" alt="">{{else}}<span class="avatar sm {{tileHue .Banner.Author}}">{{if .Banner.Initial}}{{.Banner.Initial}}{{else}}{{initial .Banner.Author}}{{end}}</span>{{end}}<span class="userchip-name">{{.Banner.Author}}</span>{{if .Banner.AuthorURL}}</a>{{end}}</span>{{end}}
93 93 <span>{{t "mr.wantsLead"}}</span>
94 94 <strong>{{.Banner.CommitPhrase}}</strong>
95 95 <span>{{t "mr.wantsFrom"}}</span>
@@ -434,7 +434,7 @@
434 434 {{template "pipenav" $}}
435 435 {{with .JobPage}}
436 436 {{$page := .}}
437 <p class="jobhead"><span class="status {{.Status}}" data-job-status><span class="mark"></span><span data-job-label>{{.Label}}</span></span>{{if .Queue}} <span class="queue" data-queue>{{.Queue}}</span>{{end}} <span class="muted">{{t "pipe.started"}} {{.When}} {{t "pipe.by"}}</span> {{if .ActorURL}}<a class="avatarlink" href="{{.ActorURL}}">{{end}}{{if .Avatar}}<img class="avatar sm" src="{{.Avatar}}" alt="">{{else if .Actor}}<span class="avatar sm">{{.Initial}}</span>{{end}} <strong>{{.Actor}}</strong>{{if .ActorURL}}</a>{{end}}</p>
437 <p class="jobhead"><span class="status {{.Status}}" data-job-status><span class="mark"></span><span data-job-label>{{.Label}}</span></span>{{if .Queue}} <span class="queue" data-queue>{{.Queue}}</span>{{end}} <span class="muted">{{t "pipe.started"}} {{.When}} {{t "pipe.by"}}</span> {{template "userchip" .}}</p>
438 438 <div class="joblayout">
439 439 <section class="console-wrap" data-console data-log-url="/{{$.Repo.FullPath}}/-/pipelines/{{.Pipe.ID}}/jobs/{{.Job.ID}}/log" data-offset="{{.LogBytes}}" data-running="{{if .Running}}1{{end}}">
440 440 <div class="conbar">
@@ -663,11 +663,13 @@
663 663 <label class="tiphost"><span class="rui-lbl">{{t "stale.repo.label"}} {{tip "stale.repo.tip"}}</span>
664 664 <input type="number" name="stale_manual_days" min="0" max="3650" value="{{if ge .StaleDays 0}}{{.StaleDays}}{{end}}" placeholder="{{t "stale.repo.inherit" .StaleDaysDefault}}">
665 665 </label>
666 <label><input type="checkbox" name="ci_paused" value="1"{{if .Repo.CIPaused}} checked{{end}}> {{t "ci.pause.label"}}</label>
667 <p class="muted">{{t "ci.pause.hint"}}</p>
666 668 <button type="submit">{{t "action.save"}}</button>
667 669 </form>
668 670 <form class="panel" method="post" action="/{{.Repo.FullPath}}/-/logo" enctype="multipart/form-data">
669 671 <input type="hidden" name="csrf" value="{{.CSRF}}">
670 <label>{{t "logo.file"}} <input type="file" name="logo" accept="image/png,image/jpeg,image/gif,image/svg+xml,.svg" required></label>
672 <label>{{t "logo.file"}} <input type="file" name="logo" accept="image/png,image/jpeg,image/gif,image/svg+xml,image/x-icon,.svg,.ico" required></label>
671 673 <p class="muted">{{t "logo.hint"}}</p>
672 674 <button type="submit">{{t "action.save"}}</button>
673 675 </form>
@@ -955,7 +957,7 @@
955 957 {{template "approvalform" .}}
956 958 <form class="panel" method="post" action="/groups/{{.Group.Path}}/logo" enctype="multipart/form-data">
957 959 <input type="hidden" name="csrf" value="{{.CSRF}}">
958 <label>{{t "logo.file"}} <input type="file" name="logo" accept="image/png,image/jpeg,image/gif,image/svg+xml,.svg" required></label>
960 <label>{{t "logo.file"}} <input type="file" name="logo" accept="image/png,image/jpeg,image/gif,image/svg+xml,image/x-icon,.svg,.ico" required></label>
959 961 <p class="muted">{{t "logo.hint"}}</p>
960 962 <button type="submit">{{t "action.save"}}</button>
961 963 </form>
@@ -89,7 +89,7 @@
89 <p class="mrmeta">!{{.MR.Number}}{{if .Banner}} · {{.Banner.WhenLabel}}{{end}}</p>
89 <p class="mrmeta">!{{.MR.Number}}{{if .Banner}} · {{.Banner.WhenLabel}}{{end}}</p>
90 {{if .Banner}}
90 {{if .Banner}}
91 <p class="mrwant">
91 <p class="mrwant">
92 {{if .Banner.AuthorURL}}<a class="who" href="{{.Banner.AuthorURL}}">{{if .Banner.Avatar}}<img class="avatar sm" src="{{.Banner.Avatar}}" alt="">{{else}}<span class="avatar sm">{{.Banner.Initial}}</span>{{end}}{{.Banner.Author}}</a>{{else if .Banner.Author}}<span class="avatar sm">{{.Banner.Initial}}</span> <strong>{{.Banner.Author}}</strong>{{end}}
92 {{if .Banner.Author}}<span class="userchip">{{if .Banner.AuthorURL}}<a class="userchip-link" href="{{.Banner.AuthorURL}}">{{end}}{{if .Banner.Avatar}}<img class="avatar sm" src="{{.Banner.Avatar}}" alt="">{{else}}<span class="avatar sm {{tileHue .Banner.Author}}">{{if .Banner.Initial}}{{.Banner.Initial}}{{else}}{{initial .Banner.Author}}{{end}}</span>{{end}}<span class="userchip-name">{{.Banner.Author}}</span>{{if .Banner.AuthorURL}}</a>{{end}}</span>{{end}}
93 <span>{{t "mr.wantsLead"}}</span>
93 <span>{{t "mr.wantsLead"}}</span>
94 <strong>{{.Banner.CommitPhrase}}</strong>
94 <strong>{{.Banner.CommitPhrase}}</strong>
95 <span>{{t "mr.wantsFrom"}}</span>
95 <span>{{t "mr.wantsFrom"}}</span>
@@ -434,7 +434,7 @@
434{{template "pipenav" $}}
434{{template "pipenav" $}}
435{{with .JobPage}}
435{{with .JobPage}}
436{{$page := .}}
436{{$page := .}}
437<p class="jobhead"><span class="status {{.Status}}" data-job-status><span class="mark"></span><span data-job-label>{{.Label}}</span></span>{{if .Queue}} <span class="queue" data-queue>{{.Queue}}</span>{{end}} <span class="muted">{{t "pipe.started"}} {{.When}} {{t "pipe.by"}}</span> {{if .ActorURL}}<a class="avatarlink" href="{{.ActorURL}}">{{end}}{{if .Avatar}}<img class="avatar sm" src="{{.Avatar}}" alt="">{{else if .Actor}}<span class="avatar sm">{{.Initial}}</span>{{end}} <strong>{{.Actor}}</strong>{{if .ActorURL}}</a>{{end}}</p>
437<p class="jobhead"><span class="status {{.Status}}" data-job-status><span class="mark"></span><span data-job-label>{{.Label}}</span></span>{{if .Queue}} <span class="queue" data-queue>{{.Queue}}</span>{{end}} <span class="muted">{{t "pipe.started"}} {{.When}} {{t "pipe.by"}}</span> {{template "userchip" .}}</p>
438<div class="joblayout">
438<div class="joblayout">
439 <section class="console-wrap" data-console data-log-url="/{{$.Repo.FullPath}}/-/pipelines/{{.Pipe.ID}}/jobs/{{.Job.ID}}/log" data-offset="{{.LogBytes}}" data-running="{{if .Running}}1{{end}}">
439 <section class="console-wrap" data-console data-log-url="/{{$.Repo.FullPath}}/-/pipelines/{{.Pipe.ID}}/jobs/{{.Job.ID}}/log" data-offset="{{.LogBytes}}" data-running="{{if .Running}}1{{end}}">
440 <div class="conbar">
440 <div class="conbar">
@@ -663,11 +663,13 @@
663 <label class="tiphost"><span class="rui-lbl">{{t "stale.repo.label"}} {{tip "stale.repo.tip"}}</span>
663 <label class="tiphost"><span class="rui-lbl">{{t "stale.repo.label"}} {{tip "stale.repo.tip"}}</span>
664 <input type="number" name="stale_manual_days" min="0" max="3650" value="{{if ge .StaleDays 0}}{{.StaleDays}}{{end}}" placeholder="{{t "stale.repo.inherit" .StaleDaysDefault}}">
664 <input type="number" name="stale_manual_days" min="0" max="3650" value="{{if ge .StaleDays 0}}{{.StaleDays}}{{end}}" placeholder="{{t "stale.repo.inherit" .StaleDaysDefault}}">
665 </label>
665 </label>
666 <label><input type="checkbox" name="ci_paused" value="1"{{if .Repo.CIPaused}} checked{{end}}> {{t "ci.pause.label"}}</label>
667 <p class="muted">{{t "ci.pause.hint"}}</p>
666 <button type="submit">{{t "action.save"}}</button>
668 <button type="submit">{{t "action.save"}}</button>
667</form>
669</form>
668<form class="panel" method="post" action="/{{.Repo.FullPath}}/-/logo" enctype="multipart/form-data">
670<form class="panel" method="post" action="/{{.Repo.FullPath}}/-/logo" enctype="multipart/form-data">
669 <input type="hidden" name="csrf" value="{{.CSRF}}">
671 <input type="hidden" name="csrf" value="{{.CSRF}}">
670 <label>{{t "logo.file"}} <input type="file" name="logo" accept="image/png,image/jpeg,image/gif,image/svg+xml,.svg" required></label>
672 <label>{{t "logo.file"}} <input type="file" name="logo" accept="image/png,image/jpeg,image/gif,image/svg+xml,image/x-icon,.svg,.ico" required></label>
671 <p class="muted">{{t "logo.hint"}}</p>
673 <p class="muted">{{t "logo.hint"}}</p>
672 <button type="submit">{{t "action.save"}}</button>
674 <button type="submit">{{t "action.save"}}</button>
673</form>
675</form>
@@ -955,7 +957,7 @@
955{{template "approvalform" .}}
957{{template "approvalform" .}}
956<form class="panel" method="post" action="/groups/{{.Group.Path}}/logo" enctype="multipart/form-data">
958<form class="panel" method="post" action="/groups/{{.Group.Path}}/logo" enctype="multipart/form-data">
957 <input type="hidden" name="csrf" value="{{.CSRF}}">
959 <input type="hidden" name="csrf" value="{{.CSRF}}">
958 <label>{{t "logo.file"}} <input type="file" name="logo" accept="image/png,image/jpeg,image/gif,image/svg+xml,.svg" required></label>
960 <label>{{t "logo.file"}} <input type="file" name="logo" accept="image/png,image/jpeg,image/gif,image/svg+xml,image/x-icon,.svg,.ico" required></label>
959 <p class="muted">{{t "logo.hint"}}</p>
961 <p class="muted">{{t "logo.hint"}}</p>
960 <button type="submit">{{t "action.save"}}</button>
962 <button type="submit">{{t "action.save"}}</button>
961</form>
963</form>
internal/server/templates/pages.html +6 −0
@@ -420,6 +420,12 @@
420 420 {{if .RevProtected}}<svg class="vis" viewBox="0 0 16 16" aria-label="{{t "vis.protected"}}"><rect x="3.5" y="7" width="9" height="6.5" rx="1" fill="none" stroke="currentColor" stroke-width="1.4"/><path fill="none" stroke="currentColor" stroke-width="1.4" d="M5.5 7V5a2.5 2.5 0 0 1 5 0v2"/></svg>{{end}}
421 421 {{end}}
422 422
423 {{define "userchip"}}
424 {{- if .Actor -}}
425 <span class="userchip">{{if .ActorURL}}<a class="userchip-link" href="{{.ActorURL}}">{{end}}{{if .Avatar}}<img class="avatar sm" src="{{.Avatar}}" alt="">{{else}}<span class="avatar sm {{tileHue .Actor}}">{{if .Initial}}{{.Initial}}{{else}}{{initial .Actor}}{{end}}</span>{{end}}<span class="userchip-name">{{.Actor}}</span>{{if .ActorURL}}</a>{{end}}</span>
426 {{- end -}}
427 {{end}}
428
423 429 {{define "avatar"}}
424 430 {{if .UserURL}}<a class="avatarlink" href="{{.UserURL}}">{{end}}
425 431 {{if .Avatar}}<img class="avatar" src="{{.Avatar}}" alt="">{{else}}<span class="avatar">{{if .Initial}}{{.Initial}}{{else}}{{initial .Author}}{{end}}</span>{{end}}
@@ -420,6 +420,12 @@
420{{if .RevProtected}}<svg class="vis" viewBox="0 0 16 16" aria-label="{{t "vis.protected"}}"><rect x="3.5" y="7" width="9" height="6.5" rx="1" fill="none" stroke="currentColor" stroke-width="1.4"/><path fill="none" stroke="currentColor" stroke-width="1.4" d="M5.5 7V5a2.5 2.5 0 0 1 5 0v2"/></svg>{{end}}
420{{if .RevProtected}}<svg class="vis" viewBox="0 0 16 16" aria-label="{{t "vis.protected"}}"><rect x="3.5" y="7" width="9" height="6.5" rx="1" fill="none" stroke="currentColor" stroke-width="1.4"/><path fill="none" stroke="currentColor" stroke-width="1.4" d="M5.5 7V5a2.5 2.5 0 0 1 5 0v2"/></svg>{{end}}
421{{end}}
421{{end}}
422
422
423{{define "userchip"}}
424{{- if .Actor -}}
425<span class="userchip">{{if .ActorURL}}<a class="userchip-link" href="{{.ActorURL}}">{{end}}{{if .Avatar}}<img class="avatar sm" src="{{.Avatar}}" alt="">{{else}}<span class="avatar sm {{tileHue .Actor}}">{{if .Initial}}{{.Initial}}{{else}}{{initial .Actor}}{{end}}</span>{{end}}<span class="userchip-name">{{.Actor}}</span>{{if .ActorURL}}</a>{{end}}</span>
426{{- end -}}
427{{end}}
428
423{{define "avatar"}}
429{{define "avatar"}}
424{{if .UserURL}}<a class="avatarlink" href="{{.UserURL}}">{{end}}
430{{if .UserURL}}<a class="avatarlink" href="{{.UserURL}}">{{end}}
425{{if .Avatar}}<img class="avatar" src="{{.Avatar}}" alt="">{{else}}<span class="avatar">{{if .Initial}}{{.Initial}}{{else}}{{initial .Author}}{{end}}</span>{{end}}
431{{if .Avatar}}<img class="avatar" src="{{.Avatar}}" alt="">{{else}}<span class="avatar">{{if .Initial}}{{.Initial}}{{else}}{{initial .Author}}{{end}}</span>{{end}}
internal/server/user_avatar.go added +99 −0
@@ -0,0 +1,99 @@
1 package server
2
3 import (
4 "bytes"
5 "context"
6 "errors"
7 "net/http"
8 "os"
9 "path/filepath"
10 "strconv"
11 "strings"
12 "time"
13
14 "gitlab.com/Timfa/bluegit/internal/auth"
15 "gitlab.com/Timfa/bluegit/internal/logo"
16 "gitlab.com/Timfa/bluegit/internal/store"
17 )
18
19 func (s *Server) maybeRefreshEntraAvatar(ctx context.Context, user store.User, token string) store.User {
20 e, ok := s.Auth.(*auth.Entra)
21 if !ok || strings.TrimSpace(token) == "" || user.ID == 0 {
22 return user
23 }
24 data, err := e.FetchPhoto(ctx, token)
25 if errors.Is(err, auth.ErrNoPhoto) {
26 if user.AvatarSource == "entra" {
27 _ = s.Store.SetUserAvatar(ctx, user.ID, "", "", "")
28 user.AvatarURL, user.AvatarSource, user.AvatarMIME = "", "", ""
29 }
30 return user
31 }
32 if err != nil || len(data) == 0 {
33 return user
34 }
35 if err := s.storeUserAvatar(ctx, user, data, "entra"); err != nil {
36 if s.Log != nil {
37 s.Log.Info("entra avatar", "user", user.Username, "err", err)
38 }
39 return user
40 }
41 if next, err := s.Store.UserByID(ctx, user.ID); err == nil {
42 return next
43 }
44 return user
45 }
46
47 func (s *Server) storeUserAvatar(ctx context.Context, user store.User, raw []byte, source string) error {
48 if user.AvatarSource == "upload" && source != "upload" {
49 return nil
50 }
51 data, mime, err := logo.Normalize(raw)
52 if err != nil {
53 return err
54 }
55 path, err := s.userAvatarPath(user.ID)
56 if err != nil {
57 return err
58 }
59 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
60 return err
61 }
62 if err := os.WriteFile(path, data, 0o644); err != nil {
63 return err
64 }
65 url := "/users/" + user.Username + "/avatar"
66 return s.Store.SetUserAvatar(ctx, user.ID, url, source, mime)
67 }
68
69 func (s *Server) userAvatarPath(id int64) (string, error) {
70 if s.StateDir == "" {
71 return "", errors.New("geen state-map voor avatars")
72 }
73 return filepath.Join(s.StateDir, "avatars", "user-"+strconv.FormatInt(id, 10)), nil
74 }
75
76 func (s *Server) userAvatar(w http.ResponseWriter, r *http.Request) {
77 u, err := s.Store.UserByUsername(r.Context(), r.PathValue("username"))
78 if err != nil || u.AvatarURL == "" || !strings.HasPrefix(u.AvatarURL, "/users/") {
79 http.NotFound(w, r)
80 return
81 }
82 path, err := s.userAvatarPath(u.ID)
83 if err != nil {
84 http.NotFound(w, r)
85 return
86 }
87 data, err := os.ReadFile(path)
88 if err != nil {
89 http.NotFound(w, r)
90 return
91 }
92 mime := u.AvatarMIME
93 if mime == "" {
94 mime = http.DetectContentType(data)
95 }
96 w.Header().Set("Content-Type", mime)
97 w.Header().Set("Cache-Control", "private, max-age=60")
98 http.ServeContent(w, r, "", time.Time{}, bytes.NewReader(data))
99 }
@@ -0,0 +1,99 @@
1package server
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "net/http"
8 "os"
9 "path/filepath"
10 "strconv"
11 "strings"
12 "time"
13
14 "gitlab.com/Timfa/bluegit/internal/auth"
15 "gitlab.com/Timfa/bluegit/internal/logo"
16 "gitlab.com/Timfa/bluegit/internal/store"
17)
18
19func (s *Server) maybeRefreshEntraAvatar(ctx context.Context, user store.User, token string) store.User {
20 e, ok := s.Auth.(*auth.Entra)
21 if !ok || strings.TrimSpace(token) == "" || user.ID == 0 {
22 return user
23 }
24 data, err := e.FetchPhoto(ctx, token)
25 if errors.Is(err, auth.ErrNoPhoto) {
26 if user.AvatarSource == "entra" {
27 _ = s.Store.SetUserAvatar(ctx, user.ID, "", "", "")
28 user.AvatarURL, user.AvatarSource, user.AvatarMIME = "", "", ""
29 }
30 return user
31 }
32 if err != nil || len(data) == 0 {
33 return user
34 }
35 if err := s.storeUserAvatar(ctx, user, data, "entra"); err != nil {
36 if s.Log != nil {
37 s.Log.Info("entra avatar", "user", user.Username, "err", err)
38 }
39 return user
40 }
41 if next, err := s.Store.UserByID(ctx, user.ID); err == nil {
42 return next
43 }
44 return user
45}
46
47func (s *Server) storeUserAvatar(ctx context.Context, user store.User, raw []byte, source string) error {
48 if user.AvatarSource == "upload" && source != "upload" {
49 return nil
50 }
51 data, mime, err := logo.Normalize(raw)
52 if err != nil {
53 return err
54 }
55 path, err := s.userAvatarPath(user.ID)
56 if err != nil {
57 return err
58 }
59 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
60 return err
61 }
62 if err := os.WriteFile(path, data, 0o644); err != nil {
63 return err
64 }
65 url := "/users/" + user.Username + "/avatar"
66 return s.Store.SetUserAvatar(ctx, user.ID, url, source, mime)
67}
68
69func (s *Server) userAvatarPath(id int64) (string, error) {
70 if s.StateDir == "" {
71 return "", errors.New("geen state-map voor avatars")
72 }
73 return filepath.Join(s.StateDir, "avatars", "user-"+strconv.FormatInt(id, 10)), nil
74}
75
76func (s *Server) userAvatar(w http.ResponseWriter, r *http.Request) {
77 u, err := s.Store.UserByUsername(r.Context(), r.PathValue("username"))
78 if err != nil || u.AvatarURL == "" || !strings.HasPrefix(u.AvatarURL, "/users/") {
79 http.NotFound(w, r)
80 return
81 }
82 path, err := s.userAvatarPath(u.ID)
83 if err != nil {
84 http.NotFound(w, r)
85 return
86 }
87 data, err := os.ReadFile(path)
88 if err != nil {
89 http.NotFound(w, r)
90 return
91 }
92 mime := u.AvatarMIME
93 if mime == "" {
94 mime = http.DetectContentType(data)
95 }
96 w.Header().Set("Content-Type", mime)
97 w.Header().Set("Cache-Control", "private, max-age=60")
98 http.ServeContent(w, r, "", time.Time{}, bytes.NewReader(data))
99}
internal/store/repos.go +26 −6
@@ -56,6 +56,8 @@ type Repo struct {
56 56 ReleaseVisibility string
57 57 // PushedAt is het moment van de laatste push. Nul: nog nooit gepusht.
58 58 PushedAt time.Time
59 // CIPaused: geen nieuwe pipelines in de wachtrij (push, MR, handmatig).
60 CIPaused bool
59 61 }
60 62
61 63 // ReleasesPublic meldt of releases (pagina, notities, assets) voor
@@ -323,14 +325,15 @@ func (s *Store) RepoByPath(ctx context.Context, owner, name string) (Repo, error
323 325 const repoSelect = `
324 326 SELECT r.id, r.owner_kind, r.owner_id,
325 327 CASE r.owner_kind WHEN 'user' THEN (SELECT username FROM users WHERE id = r.owner_id) ELSE (SELECT path FROM groups WHERE id = r.owner_id) END,
326 r.name, r.description, r.default_branch, r.visibility, r.created_at, r.logo_mime, r.release_visibility, r.pushed_at
328 r.name, r.description, r.default_branch, r.visibility, r.created_at, r.logo_mime, r.release_visibility, r.pushed_at, r.ci_paused
327 329 FROM repos r`
328 330
329 331 func scanRepo(row *sql.Row) (Repo, error) {
330 332 var r Repo
331 333 var created, pushed string
332 334 var owner sql.NullString
333 if err := row.Scan(&r.ID, &r.OwnerKind, &r.OwnerID, &owner, &r.Name, &r.Description, &r.DefaultBranch, &r.Visibility, &created, &r.LogoMIME, &r.ReleaseVisibility, &pushed); err != nil {
335 var paused int
336 if err := row.Scan(&r.ID, &r.OwnerKind, &r.OwnerID, &owner, &r.Name, &r.Description, &r.DefaultBranch, &r.Visibility, &created, &r.LogoMIME, &r.ReleaseVisibility, &pushed, &paused); err != nil {
334 337 if errors.Is(err, sql.ErrNoRows) {
335 338 return Repo{}, errNotFound
336 339 }
@@ -341,6 +344,7 @@ func scanRepo(row *sql.Row) (Repo, error) {
341 344 if pushed != "" {
342 345 r.PushedAt = parseTime(pushed)
343 346 }
347 r.CIPaused = paused == 1
344 348 return r, nil
345 349 }
346 350
@@ -353,6 +357,23 @@ func (s *Store) UpdateRepo(ctx context.Context, id int64, description, visibilit
353 357 return err
354 358 }
355 359
360 // SetDefaultBranch zet de standaardbranch in de metadata. De aanroeper
361 // zet HEAD in de bare repository.
362 func (s *Store) SetDefaultBranch(ctx context.Context, id int64, branch string) error {
363 branch = strings.TrimSpace(branch)
364 if branch == "" {
365 return i18n.E("err.branchMissing")
366 }
367 _, err := s.db.ExecContext(ctx, `UPDATE repos SET default_branch = ? WHERE id = ?`, branch, id)
368 return err
369 }
370
371 // SetRepoCIPaused zet of er nieuwe pipelines mogen worden ingepland.
372 func (s *Store) SetRepoCIPaused(ctx context.Context, id int64, paused bool) error {
373 _, err := s.db.ExecContext(ctx, `UPDATE repos SET ci_paused = ? WHERE id = ?`, boolInt(paused), id)
374 return err
375 }
376
356 377 // DeleteRepo verwijdert de metadata. Bestanden verwijdert de aanroeper.
357 378 func (s *Store) DeleteRepo(ctx context.Context, id int64) error {
358 379 // Forks blijven bestaan als zelfstandige repositories.
@@ -447,7 +468,8 @@ func scanRepos(rows *sql.Rows) ([]Repo, error) {
447 468 var r Repo
448 469 var created, pushed string
449 470 var owner sql.NullString
450 if err := rows.Scan(&r.ID, &r.OwnerKind, &r.OwnerID, &owner, &r.Name, &r.Description, &r.DefaultBranch, &r.Visibility, &created, &r.LogoMIME, &r.ReleaseVisibility, &pushed); err != nil {
471 var paused int
472 if err := rows.Scan(&r.ID, &r.OwnerKind, &r.OwnerID, &owner, &r.Name, &r.Description, &r.DefaultBranch, &r.Visibility, &created, &r.LogoMIME, &r.ReleaseVisibility, &pushed, &paused); err != nil {
451 473 return nil, err
452 474 }
453 475 r.OwnerPath = owner.String
@@ -455,9 +477,7 @@ func scanRepos(rows *sql.Rows) ([]Repo, error) {
455 477 if pushed != "" {
456 478 r.PushedAt = parseTime(pushed)
457 479 }
458 if pushed != "" {
459 r.PushedAt = parseTime(pushed)
460 }
480 r.CIPaused = paused == 1
461 481 out = append(out, r)
462 482 }
463 483 return out, rows.Err()
@@ -56,6 +56,8 @@ type Repo struct {
56 ReleaseVisibility string
56 ReleaseVisibility string
57 // PushedAt is het moment van de laatste push. Nul: nog nooit gepusht.
57 // PushedAt is het moment van de laatste push. Nul: nog nooit gepusht.
58 PushedAt time.Time
58 PushedAt time.Time
59 // CIPaused: geen nieuwe pipelines in de wachtrij (push, MR, handmatig).
60 CIPaused bool
59}
61}
60
62
61// ReleasesPublic meldt of releases (pagina, notities, assets) voor
63// ReleasesPublic meldt of releases (pagina, notities, assets) voor
@@ -323,14 +325,15 @@ func (s *Store) RepoByPath(ctx context.Context, owner, name string) (Repo, error
323const repoSelect = `
325const repoSelect = `
324SELECT r.id, r.owner_kind, r.owner_id,
326SELECT r.id, r.owner_kind, r.owner_id,
325 CASE r.owner_kind WHEN 'user' THEN (SELECT username FROM users WHERE id = r.owner_id) ELSE (SELECT path FROM groups WHERE id = r.owner_id) END,
327 CASE r.owner_kind WHEN 'user' THEN (SELECT username FROM users WHERE id = r.owner_id) ELSE (SELECT path FROM groups WHERE id = r.owner_id) END,
326 r.name, r.description, r.default_branch, r.visibility, r.created_at, r.logo_mime, r.release_visibility, r.pushed_at
328 r.name, r.description, r.default_branch, r.visibility, r.created_at, r.logo_mime, r.release_visibility, r.pushed_at, r.ci_paused
327FROM repos r`
329FROM repos r`
328
330
329func scanRepo(row *sql.Row) (Repo, error) {
331func scanRepo(row *sql.Row) (Repo, error) {
330 var r Repo
332 var r Repo
331 var created, pushed string
333 var created, pushed string
332 var owner sql.NullString
334 var owner sql.NullString
333 if err := row.Scan(&r.ID, &r.OwnerKind, &r.OwnerID, &owner, &r.Name, &r.Description, &r.DefaultBranch, &r.Visibility, &created, &r.LogoMIME, &r.ReleaseVisibility, &pushed); err != nil {
335 var paused int
336 if err := row.Scan(&r.ID, &r.OwnerKind, &r.OwnerID, &owner, &r.Name, &r.Description, &r.DefaultBranch, &r.Visibility, &created, &r.LogoMIME, &r.ReleaseVisibility, &pushed, &paused); err != nil {
334 if errors.Is(err, sql.ErrNoRows) {
337 if errors.Is(err, sql.ErrNoRows) {
335 return Repo{}, errNotFound
338 return Repo{}, errNotFound
336 }
339 }
@@ -341,6 +344,7 @@ func scanRepo(row *sql.Row) (Repo, error) {
341 if pushed != "" {
344 if pushed != "" {
342 r.PushedAt = parseTime(pushed)
345 r.PushedAt = parseTime(pushed)
343 }
346 }
347 r.CIPaused = paused == 1
344 return r, nil
348 return r, nil
345}
349}
346
350
@@ -353,6 +357,23 @@ func (s *Store) UpdateRepo(ctx context.Context, id int64, description, visibilit
353 return err
357 return err
354}
358}
355
359
360// SetDefaultBranch zet de standaardbranch in de metadata. De aanroeper
361// zet HEAD in de bare repository.
362func (s *Store) SetDefaultBranch(ctx context.Context, id int64, branch string) error {
363 branch = strings.TrimSpace(branch)
364 if branch == "" {
365 return i18n.E("err.branchMissing")
366 }
367 _, err := s.db.ExecContext(ctx, `UPDATE repos SET default_branch = ? WHERE id = ?`, branch, id)
368 return err
369}
370
371// SetRepoCIPaused zet of er nieuwe pipelines mogen worden ingepland.
372func (s *Store) SetRepoCIPaused(ctx context.Context, id int64, paused bool) error {
373 _, err := s.db.ExecContext(ctx, `UPDATE repos SET ci_paused = ? WHERE id = ?`, boolInt(paused), id)
374 return err
375}
376
356// DeleteRepo verwijdert de metadata. Bestanden verwijdert de aanroeper.
377// DeleteRepo verwijdert de metadata. Bestanden verwijdert de aanroeper.
357func (s *Store) DeleteRepo(ctx context.Context, id int64) error {
378func (s *Store) DeleteRepo(ctx context.Context, id int64) error {
358 // Forks blijven bestaan als zelfstandige repositories.
379 // Forks blijven bestaan als zelfstandige repositories.
@@ -447,7 +468,8 @@ func scanRepos(rows *sql.Rows) ([]Repo, error) {
447 var r Repo
468 var r Repo
448 var created, pushed string
469 var created, pushed string
449 var owner sql.NullString
470 var owner sql.NullString
450 if err := rows.Scan(&r.ID, &r.OwnerKind, &r.OwnerID, &owner, &r.Name, &r.Description, &r.DefaultBranch, &r.Visibility, &created, &r.LogoMIME, &r.ReleaseVisibility, &pushed); err != nil {
471 var paused int
472 if err := rows.Scan(&r.ID, &r.OwnerKind, &r.OwnerID, &owner, &r.Name, &r.Description, &r.DefaultBranch, &r.Visibility, &created, &r.LogoMIME, &r.ReleaseVisibility, &pushed, &paused); err != nil {
451 return nil, err
473 return nil, err
452 }
474 }
453 r.OwnerPath = owner.String
475 r.OwnerPath = owner.String
@@ -455,9 +477,7 @@ func scanRepos(rows *sql.Rows) ([]Repo, error) {
455 if pushed != "" {
477 if pushed != "" {
456 r.PushedAt = parseTime(pushed)
478 r.PushedAt = parseTime(pushed)
457 }
479 }
458 if pushed != "" {
480 r.CIPaused = paused == 1
459 r.PushedAt = parseTime(pushed)
460 }
461 out = append(out, r)
481 out = append(out, r)
462 }
482 }
463 return out, rows.Err()
483 return out, rows.Err()
internal/store/store.go +36 −17
@@ -119,6 +119,9 @@ func (s *Store) migrate() error {
119 119 `ALTER TABLE groups ADD COLUMN builtin_first INTEGER NOT NULL DEFAULT 0`,
120 120 `ALTER TABLE runners ADD COLUMN paused INTEGER NOT NULL DEFAULT 0`,
121 121 `ALTER TABLE runners ADD COLUMN draining INTEGER NOT NULL DEFAULT 0`,
122 `ALTER TABLE repos ADD COLUMN ci_paused INTEGER NOT NULL DEFAULT 0`,
123 `ALTER TABLE users ADD COLUMN avatar_source TEXT NOT NULL DEFAULT ''`,
124 `ALTER TABLE users ADD COLUMN avatar_mime TEXT NOT NULL DEFAULT ''`,
122 125 }
123 126 for _, q := range alters {
124 127 if _, err := s.db.Exec(q); err != nil && !strings.Contains(strings.ToLower(err.Error()), "duplicate column") {
@@ -549,6 +552,8 @@ type User struct {
549 552 AuthID int64
550 553 Username string
551 554 AvatarURL string
555 AvatarSource string // "", "remote", "entra" of "upload"
556 AvatarMIME string
552 557 AuthAdmin bool
553 558 InstanceAdmin bool
554 559 Language string
@@ -589,8 +594,12 @@ func (s *Store) UpsertUser(ctx context.Context, authID int64, username, avatar s
589 594 if count == 0 {
590 595 admin = 1
591 596 }
592 res, err := tx.ExecContext(ctx, `INSERT INTO users (auth_id, username, avatar_url, auth_admin, instance_admin, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)`,
593 authID, username, avatar, boolInt(authAdmin), admin, ts, ts)
597 src := ""
598 if avatar != "" {
599 src = "remote"
600 }
601 res, err := tx.ExecContext(ctx, `INSERT INTO users (auth_id, username, avatar_url, avatar_source, auth_admin, instance_admin, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
602 authID, username, avatar, src, boolInt(authAdmin), admin, ts, ts)
594 603 if err != nil {
595 604 return User{}, err
596 605 }
@@ -598,15 +607,11 @@ func (s *Store) UpsertUser(ctx context.Context, authID int64, username, avatar s
598 607 } else if err != nil {
599 608 return User{}, err
600 609 } else {
601 if _, err := tx.ExecContext(ctx, `UPDATE users SET username = ?, avatar_url = ?, auth_admin = ?, updated_at = ? WHERE id = ? AND username = ?`,
602 username, avatar, boolInt(authAdmin), ts, existingID, username); err != nil {
603 return User{}, err
604 }
605 // Naamwijziging alleen als de nieuwe naam vrij is en gelijk blijft als hij botst.
606 var current string
607 if err := tx.QueryRowContext(ctx, `SELECT username FROM users WHERE id = ?`, existingID).Scan(&current); err != nil {
610 var current, source string
611 if err := tx.QueryRowContext(ctx, `SELECT username, avatar_source FROM users WHERE id = ?`, existingID).Scan(&current, &source); err != nil {
608 612 return User{}, err
609 613 }
614 newName := current
610 615 if current != username {
611 616 var taken int
612 617 if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM users WHERE username = ? AND id <> ?`, username, existingID).Scan(&taken); err != nil {
@@ -617,12 +622,19 @@ func (s *Store) UpsertUser(ctx context.Context, authID int64, username, avatar s
617 622 return User{}, err
618 623 }
619 624 if taken == 0 && groupTaken == 0 {
620 if _, err := tx.ExecContext(ctx, `UPDATE users SET username = ?, avatar_url = ?, auth_admin = ?, updated_at = ? WHERE id = ?`,
621 username, avatar, boolInt(authAdmin), ts, existingID); err != nil {
622 return User{}, err
623 }
624 } else if _, err := tx.ExecContext(ctx, `UPDATE users SET avatar_url = ?, auth_admin = ?, updated_at = ? WHERE id = ?`,
625 avatar, boolInt(authAdmin), ts, existingID); err != nil {
625 newName = username
626 }
627 }
628 // Een handmatig geüploade avatar nooit overschrijven. Een lege
629 // avatar-URL (Entra zonder foto) wist een bestaande ook niet.
630 if source == "upload" || avatar == "" {
631 if _, err := tx.ExecContext(ctx, `UPDATE users SET username = ?, auth_admin = ?, updated_at = ? WHERE id = ?`,
632 newName, boolInt(authAdmin), ts, existingID); err != nil {
633 return User{}, err
634 }
635 } else {
636 if _, err := tx.ExecContext(ctx, `UPDATE users SET username = ?, avatar_url = ?, avatar_source = ?, auth_admin = ?, updated_at = ? WHERE id = ?`,
637 newName, avatar, "remote", boolInt(authAdmin), ts, existingID); err != nil {
626 638 return User{}, err
627 639 }
628 640 }
@@ -687,7 +699,14 @@ func (s *Store) UserByUsername(ctx context.Context, username string) (User, erro
687 699 return scanUser(row)
688 700 }
689 701
690 const userCols = `id, auth_id, username, avatar_url, auth_admin, instance_admin, language, display_name, bio, created_at`
702 const userCols = `id, auth_id, username, avatar_url, avatar_source, avatar_mime, auth_admin, instance_admin, language, display_name, bio, created_at`
703
704 // SetUserAvatar zet de avatar-URL en de bron. source "upload" is handmatig
705 // en wordt bij een latere login niet overschreven.
706 func (s *Store) SetUserAvatar(ctx context.Context, userID int64, url, source, mime string) error {
707 _, err := s.db.ExecContext(ctx, `UPDATE users SET avatar_url = ?, avatar_source = ?, avatar_mime = ?, updated_at = ? WHERE id = ?`, url, source, mime, now(), userID)
708 return err
709 }
691 710
692 711 // SetProfile bewaart de weergavenaam en de bio. Lege tekst wist het veld.
693 712 func (s *Store) SetProfile(ctx context.Context, userID int64, name, bio string) error {
@@ -699,7 +718,7 @@ func scanUser(row interface{ Scan(...any) error }) (User, error) {
699 718 var u User
700 719 var admin, inst int
701 720 var created string
702 if err := row.Scan(&u.ID, &u.AuthID, &u.Username, &u.AvatarURL, &admin, &inst, &u.Language, &u.DisplayName, &u.Bio, &created); err != nil {
721 if err := row.Scan(&u.ID, &u.AuthID, &u.Username, &u.AvatarURL, &u.AvatarSource, &u.AvatarMIME, &admin, &inst, &u.Language, &u.DisplayName, &u.Bio, &created); err != nil {
703 722 if errors.Is(err, sql.ErrNoRows) {
704 723 return User{}, errNotFound
705 724 }
@@ -119,6 +119,9 @@ func (s *Store) migrate() error {
119 `ALTER TABLE groups ADD COLUMN builtin_first INTEGER NOT NULL DEFAULT 0`,
119 `ALTER TABLE groups ADD COLUMN builtin_first INTEGER NOT NULL DEFAULT 0`,
120 `ALTER TABLE runners ADD COLUMN paused INTEGER NOT NULL DEFAULT 0`,
120 `ALTER TABLE runners ADD COLUMN paused INTEGER NOT NULL DEFAULT 0`,
121 `ALTER TABLE runners ADD COLUMN draining INTEGER NOT NULL DEFAULT 0`,
121 `ALTER TABLE runners ADD COLUMN draining INTEGER NOT NULL DEFAULT 0`,
122 `ALTER TABLE repos ADD COLUMN ci_paused INTEGER NOT NULL DEFAULT 0`,
123 `ALTER TABLE users ADD COLUMN avatar_source TEXT NOT NULL DEFAULT ''`,
124 `ALTER TABLE users ADD COLUMN avatar_mime TEXT NOT NULL DEFAULT ''`,
122 }
125 }
123 for _, q := range alters {
126 for _, q := range alters {
124 if _, err := s.db.Exec(q); err != nil && !strings.Contains(strings.ToLower(err.Error()), "duplicate column") {
127 if _, err := s.db.Exec(q); err != nil && !strings.Contains(strings.ToLower(err.Error()), "duplicate column") {
@@ -549,6 +552,8 @@ type User struct {
549 AuthID int64
552 AuthID int64
550 Username string
553 Username string
551 AvatarURL string
554 AvatarURL string
555 AvatarSource string // "", "remote", "entra" of "upload"
556 AvatarMIME string
552 AuthAdmin bool
557 AuthAdmin bool
553 InstanceAdmin bool
558 InstanceAdmin bool
554 Language string
559 Language string
@@ -589,8 +594,12 @@ func (s *Store) UpsertUser(ctx context.Context, authID int64, username, avatar s
589 if count == 0 {
594 if count == 0 {
590 admin = 1
595 admin = 1
591 }
596 }
592 res, err := tx.ExecContext(ctx, `INSERT INTO users (auth_id, username, avatar_url, auth_admin, instance_admin, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)`,
597 src := ""
593 authID, username, avatar, boolInt(authAdmin), admin, ts, ts)
598 if avatar != "" {
599 src = "remote"
600 }
601 res, err := tx.ExecContext(ctx, `INSERT INTO users (auth_id, username, avatar_url, avatar_source, auth_admin, instance_admin, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
602 authID, username, avatar, src, boolInt(authAdmin), admin, ts, ts)
594 if err != nil {
603 if err != nil {
595 return User{}, err
604 return User{}, err
596 }
605 }
@@ -598,15 +607,11 @@ func (s *Store) UpsertUser(ctx context.Context, authID int64, username, avatar s
598 } else if err != nil {
607 } else if err != nil {
599 return User{}, err
608 return User{}, err
600 } else {
609 } else {
601 if _, err := tx.ExecContext(ctx, `UPDATE users SET username = ?, avatar_url = ?, auth_admin = ?, updated_at = ? WHERE id = ? AND username = ?`,
610 var current, source string
602 username, avatar, boolInt(authAdmin), ts, existingID, username); err != nil {
611 if err := tx.QueryRowContext(ctx, `SELECT username, avatar_source FROM users WHERE id = ?`, existingID).Scan(&current, &source); err != nil {
603 return User{}, err
604 }
605 // Naamwijziging alleen als de nieuwe naam vrij is en gelijk blijft als hij botst.
606 var current string
607 if err := tx.QueryRowContext(ctx, `SELECT username FROM users WHERE id = ?`, existingID).Scan(&current); err != nil {
608 return User{}, err
612 return User{}, err
609 }
613 }
614 newName := current
610 if current != username {
615 if current != username {
611 var taken int
616 var taken int
612 if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM users WHERE username = ? AND id <> ?`, username, existingID).Scan(&taken); err != nil {
617 if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM users WHERE username = ? AND id <> ?`, username, existingID).Scan(&taken); err != nil {
@@ -617,12 +622,19 @@ func (s *Store) UpsertUser(ctx context.Context, authID int64, username, avatar s
617 return User{}, err
622 return User{}, err
618 }
623 }
619 if taken == 0 && groupTaken == 0 {
624 if taken == 0 && groupTaken == 0 {
620 if _, err := tx.ExecContext(ctx, `UPDATE users SET username = ?, avatar_url = ?, auth_admin = ?, updated_at = ? WHERE id = ?`,
625 newName = username
621 username, avatar, boolInt(authAdmin), ts, existingID); err != nil {
626 }
622 return User{}, err
627 }
623 }
628 // Een handmatig geüploade avatar nooit overschrijven. Een lege
624 } else if _, err := tx.ExecContext(ctx, `UPDATE users SET avatar_url = ?, auth_admin = ?, updated_at = ? WHERE id = ?`,
629 // avatar-URL (Entra zonder foto) wist een bestaande ook niet.
625 avatar, boolInt(authAdmin), ts, existingID); err != nil {
630 if source == "upload" || avatar == "" {
631 if _, err := tx.ExecContext(ctx, `UPDATE users SET username = ?, auth_admin = ?, updated_at = ? WHERE id = ?`,
632 newName, boolInt(authAdmin), ts, existingID); err != nil {
633 return User{}, err
634 }
635 } else {
636 if _, err := tx.ExecContext(ctx, `UPDATE users SET username = ?, avatar_url = ?, avatar_source = ?, auth_admin = ?, updated_at = ? WHERE id = ?`,
637 newName, avatar, "remote", boolInt(authAdmin), ts, existingID); err != nil {
626 return User{}, err
638 return User{}, err
627 }
639 }
628 }
640 }
@@ -687,7 +699,14 @@ func (s *Store) UserByUsername(ctx context.Context, username string) (User, erro
687 return scanUser(row)
699 return scanUser(row)
688}
700}
689
701
690const userCols = `id, auth_id, username, avatar_url, auth_admin, instance_admin, language, display_name, bio, created_at`
702const userCols = `id, auth_id, username, avatar_url, avatar_source, avatar_mime, auth_admin, instance_admin, language, display_name, bio, created_at`
703
704// SetUserAvatar zet de avatar-URL en de bron. source "upload" is handmatig
705// en wordt bij een latere login niet overschreven.
706func (s *Store) SetUserAvatar(ctx context.Context, userID int64, url, source, mime string) error {
707 _, err := s.db.ExecContext(ctx, `UPDATE users SET avatar_url = ?, avatar_source = ?, avatar_mime = ?, updated_at = ? WHERE id = ?`, url, source, mime, now(), userID)
708 return err
709}
691
710
692// SetProfile bewaart de weergavenaam en de bio. Lege tekst wist het veld.
711// SetProfile bewaart de weergavenaam en de bio. Lege tekst wist het veld.
693func (s *Store) SetProfile(ctx context.Context, userID int64, name, bio string) error {
712func (s *Store) SetProfile(ctx context.Context, userID int64, name, bio string) error {
@@ -699,7 +718,7 @@ func scanUser(row interface{ Scan(...any) error }) (User, error) {
699 var u User
718 var u User
700 var admin, inst int
719 var admin, inst int
701 var created string
720 var created string
702 if err := row.Scan(&u.ID, &u.AuthID, &u.Username, &u.AvatarURL, &admin, &inst, &u.Language, &u.DisplayName, &u.Bio, &created); err != nil {
721 if err := row.Scan(&u.ID, &u.AuthID, &u.Username, &u.AvatarURL, &u.AvatarSource, &u.AvatarMIME, &admin, &inst, &u.Language, &u.DisplayName, &u.Bio, &created); err != nil {
703 if errors.Is(err, sql.ErrNoRows) {
722 if errors.Is(err, sql.ErrNoRows) {
704 return User{}, errNotFound
723 return User{}, errNotFound
705 }
724 }