feat(governance): sign in to the archie binary from the Vue dashboard (#2017)
The binary serves the account routes the Vue client already calls: status,
setup, password and passkey sign-in, recovery, sign-out, OIDC, account
passkeys, password and recovery codes, personal tokens and capabilities.
The API authenticates a session cookie, a personal token or the bootstrap
admin token, and unsafe requests pass cross-origin protection. The
dashboard serves the Vue app at /.
Copied from internal/webui/{accounts,passkeys,personal_tokens,
api_capabilities,auth}.go, internal/infrastructure/oidc/{flow,oidc}.go and
internal/app/archieui/account_oidc.go, which archie-ui still imports.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
14 files changed
+2241
-53
No files matched your search
+905
-3
@@ -76,6 +76,31 @@ components:
|
|||||||
truncated:
|
truncated:
|
||||||
type: boolean
|
type: boolean
|
||||||
type: object
|
type: object
|
||||||
|
AuthenticationInputBody:
|
||||||
|
additionalProperties: false
|
||||||
|
properties:
|
||||||
|
oidc_audience:
|
||||||
|
type: string
|
||||||
|
oidc_client_id:
|
||||||
|
type: string
|
||||||
|
oidc_issuer:
|
||||||
|
type: string
|
||||||
|
public_url:
|
||||||
|
type: string
|
||||||
|
required:
|
||||||
|
- public_url
|
||||||
|
type: object
|
||||||
|
ChangePasswordInputBody:
|
||||||
|
additionalProperties: false
|
||||||
|
properties:
|
||||||
|
current_password:
|
||||||
|
type: string
|
||||||
|
new_password:
|
||||||
|
type: string
|
||||||
|
required:
|
||||||
|
- current_password
|
||||||
|
- new_password
|
||||||
|
type: object
|
||||||
ChatActionDone:
|
ChatActionDone:
|
||||||
additionalProperties: false
|
additionalProperties: false
|
||||||
properties:
|
properties:
|
||||||
@@ -557,6 +582,17 @@ components:
|
|||||||
- name
|
- name
|
||||||
- kind
|
- kind
|
||||||
type: object
|
type: object
|
||||||
|
CreateTokenInputBody:
|
||||||
|
additionalProperties: false
|
||||||
|
properties:
|
||||||
|
days:
|
||||||
|
format: int64
|
||||||
|
type: integer
|
||||||
|
name:
|
||||||
|
type: string
|
||||||
|
required:
|
||||||
|
- name
|
||||||
|
type: object
|
||||||
DeliveriesAttempt:
|
DeliveriesAttempt:
|
||||||
additionalProperties: false
|
additionalProperties: false
|
||||||
properties:
|
properties:
|
||||||
@@ -934,6 +970,43 @@ components:
|
|||||||
- workflow
|
- workflow
|
||||||
- enabled
|
- enabled
|
||||||
type: object
|
type: object
|
||||||
|
GovernanceAuthStatusBody:
|
||||||
|
additionalProperties: false
|
||||||
|
properties:
|
||||||
|
instance:
|
||||||
|
type: string
|
||||||
|
oidc:
|
||||||
|
type: boolean
|
||||||
|
public_url:
|
||||||
|
type: string
|
||||||
|
setup_required:
|
||||||
|
type: boolean
|
||||||
|
user:
|
||||||
|
$ref: "#/components/schemas/GovernanceIdentity"
|
||||||
|
required:
|
||||||
|
- setup_required
|
||||||
|
- user
|
||||||
|
- oidc
|
||||||
|
- public_url
|
||||||
|
- instance
|
||||||
|
type: object
|
||||||
|
GovernanceAuthenticationSettings:
|
||||||
|
additionalProperties: false
|
||||||
|
properties:
|
||||||
|
oidc_audience:
|
||||||
|
type: string
|
||||||
|
oidc_client_id:
|
||||||
|
type: string
|
||||||
|
oidc_issuer:
|
||||||
|
type: string
|
||||||
|
public_url:
|
||||||
|
type: string
|
||||||
|
required:
|
||||||
|
- public_url
|
||||||
|
- oidc_issuer
|
||||||
|
- oidc_audience
|
||||||
|
- oidc_client_id
|
||||||
|
type: object
|
||||||
GovernanceBlackout:
|
GovernanceBlackout:
|
||||||
additionalProperties: false
|
additionalProperties: false
|
||||||
properties:
|
properties:
|
||||||
@@ -950,6 +1023,56 @@ components:
|
|||||||
- to
|
- to
|
||||||
- reason
|
- reason
|
||||||
type: object
|
type: object
|
||||||
|
GovernanceCapabilitiesBody:
|
||||||
|
additionalProperties: false
|
||||||
|
properties:
|
||||||
|
sections:
|
||||||
|
additionalProperties:
|
||||||
|
type: boolean
|
||||||
|
type: object
|
||||||
|
required:
|
||||||
|
- sections
|
||||||
|
type: object
|
||||||
|
GovernanceCreatedToken:
|
||||||
|
additionalProperties: false
|
||||||
|
properties:
|
||||||
|
id:
|
||||||
|
type: string
|
||||||
|
token:
|
||||||
|
type: string
|
||||||
|
required:
|
||||||
|
- id
|
||||||
|
- token
|
||||||
|
type: object
|
||||||
|
GovernanceIdentity:
|
||||||
|
additionalProperties: false
|
||||||
|
properties:
|
||||||
|
created_at:
|
||||||
|
format: date-time
|
||||||
|
type: string
|
||||||
|
display_name:
|
||||||
|
type: string
|
||||||
|
id:
|
||||||
|
type: string
|
||||||
|
kind:
|
||||||
|
type: string
|
||||||
|
lifecycle:
|
||||||
|
type: string
|
||||||
|
updated_at:
|
||||||
|
format: date-time
|
||||||
|
type: string
|
||||||
|
version:
|
||||||
|
format: int64
|
||||||
|
type: integer
|
||||||
|
required:
|
||||||
|
- id
|
||||||
|
- kind
|
||||||
|
- display_name
|
||||||
|
- lifecycle
|
||||||
|
- version
|
||||||
|
- created_at
|
||||||
|
- updated_at
|
||||||
|
type: object
|
||||||
GovernanceModel:
|
GovernanceModel:
|
||||||
additionalProperties: false
|
additionalProperties: false
|
||||||
properties:
|
properties:
|
||||||
@@ -977,6 +1100,38 @@ components:
|
|||||||
- model
|
- model
|
||||||
- answer
|
- answer
|
||||||
type: object
|
type: object
|
||||||
|
GovernancePasskey:
|
||||||
|
additionalProperties: false
|
||||||
|
properties:
|
||||||
|
id:
|
||||||
|
type: string
|
||||||
|
name:
|
||||||
|
type: string
|
||||||
|
required:
|
||||||
|
- id
|
||||||
|
- name
|
||||||
|
type: object
|
||||||
|
GovernancePasskeyFinishBody:
|
||||||
|
additionalProperties: false
|
||||||
|
properties:
|
||||||
|
credential: {}
|
||||||
|
name:
|
||||||
|
type: string
|
||||||
|
required:
|
||||||
|
- credential
|
||||||
|
type: object
|
||||||
|
GovernancePasskeysBody:
|
||||||
|
additionalProperties: false
|
||||||
|
properties:
|
||||||
|
passkeys:
|
||||||
|
items:
|
||||||
|
$ref: "#/components/schemas/GovernancePasskey"
|
||||||
|
type:
|
||||||
|
- array
|
||||||
|
- "null"
|
||||||
|
required:
|
||||||
|
- passkeys
|
||||||
|
type: object
|
||||||
GovernancePersonRequest:
|
GovernancePersonRequest:
|
||||||
additionalProperties: false
|
additionalProperties: false
|
||||||
properties:
|
properties:
|
||||||
@@ -998,6 +1153,55 @@ components:
|
|||||||
- authority
|
- authority
|
||||||
- identities
|
- identities
|
||||||
type: object
|
type: object
|
||||||
|
GovernancePersonalToken:
|
||||||
|
additionalProperties: false
|
||||||
|
properties:
|
||||||
|
created_at:
|
||||||
|
format: date-time
|
||||||
|
type: string
|
||||||
|
expires_at:
|
||||||
|
format: date-time
|
||||||
|
type:
|
||||||
|
- string
|
||||||
|
- "null"
|
||||||
|
id:
|
||||||
|
type: string
|
||||||
|
last_used_at:
|
||||||
|
format: date-time
|
||||||
|
type:
|
||||||
|
- string
|
||||||
|
- "null"
|
||||||
|
name:
|
||||||
|
type: string
|
||||||
|
required:
|
||||||
|
- id
|
||||||
|
- name
|
||||||
|
- created_at
|
||||||
|
- expires_at
|
||||||
|
- last_used_at
|
||||||
|
type: object
|
||||||
|
GovernanceRegistration:
|
||||||
|
additionalProperties: false
|
||||||
|
properties:
|
||||||
|
display_name:
|
||||||
|
type: string
|
||||||
|
email:
|
||||||
|
type: string
|
||||||
|
organisation_name:
|
||||||
|
type: string
|
||||||
|
password:
|
||||||
|
type: string
|
||||||
|
public_url:
|
||||||
|
type: string
|
||||||
|
role:
|
||||||
|
type: string
|
||||||
|
workspace_name:
|
||||||
|
type: string
|
||||||
|
required:
|
||||||
|
- email
|
||||||
|
- display_name
|
||||||
|
- password
|
||||||
|
type: object
|
||||||
GovernanceSettingsRequest:
|
GovernanceSettingsRequest:
|
||||||
additionalProperties: false
|
additionalProperties: false
|
||||||
properties:
|
properties:
|
||||||
@@ -1081,6 +1285,29 @@ components:
|
|||||||
- days
|
- days
|
||||||
- blackouts
|
- blackouts
|
||||||
type: object
|
type: object
|
||||||
|
GovernanceTokensBody:
|
||||||
|
additionalProperties: false
|
||||||
|
properties:
|
||||||
|
available:
|
||||||
|
type: boolean
|
||||||
|
tokens:
|
||||||
|
items:
|
||||||
|
$ref: "#/components/schemas/GovernancePersonalToken"
|
||||||
|
type:
|
||||||
|
- array
|
||||||
|
- "null"
|
||||||
|
required:
|
||||||
|
- tokens
|
||||||
|
- available
|
||||||
|
type: object
|
||||||
|
GovernanceUserBody:
|
||||||
|
additionalProperties: false
|
||||||
|
properties:
|
||||||
|
user:
|
||||||
|
$ref: "#/components/schemas/GovernanceIdentity"
|
||||||
|
required:
|
||||||
|
- user
|
||||||
|
type: object
|
||||||
JudgementAction:
|
JudgementAction:
|
||||||
additionalProperties: false
|
additionalProperties: false
|
||||||
properties:
|
properties:
|
||||||
@@ -1615,6 +1842,28 @@ components:
|
|||||||
required:
|
required:
|
||||||
- body
|
- body
|
||||||
type: object
|
type: object
|
||||||
|
RecoverInputBody:
|
||||||
|
additionalProperties: false
|
||||||
|
properties:
|
||||||
|
code:
|
||||||
|
type: string
|
||||||
|
email:
|
||||||
|
type: string
|
||||||
|
password:
|
||||||
|
type: string
|
||||||
|
required:
|
||||||
|
- email
|
||||||
|
- code
|
||||||
|
- password
|
||||||
|
type: object
|
||||||
|
RecoveryCodeReplyBody:
|
||||||
|
additionalProperties: false
|
||||||
|
properties:
|
||||||
|
code:
|
||||||
|
type: string
|
||||||
|
required:
|
||||||
|
- code
|
||||||
|
type: object
|
||||||
RenameInputBody:
|
RenameInputBody:
|
||||||
additionalProperties: false
|
additionalProperties: false
|
||||||
properties:
|
properties:
|
||||||
@@ -2090,6 +2339,17 @@ components:
|
|||||||
required:
|
required:
|
||||||
- text
|
- text
|
||||||
type: object
|
type: object
|
||||||
|
SignInInputBody:
|
||||||
|
additionalProperties: false
|
||||||
|
properties:
|
||||||
|
email:
|
||||||
|
type: string
|
||||||
|
password:
|
||||||
|
type: string
|
||||||
|
required:
|
||||||
|
- email
|
||||||
|
- password
|
||||||
|
type: object
|
||||||
SystemAdminToken:
|
SystemAdminToken:
|
||||||
additionalProperties: false
|
additionalProperties: false
|
||||||
properties:
|
properties:
|
||||||
@@ -2147,15 +2407,221 @@ components:
|
|||||||
- total_tokens
|
- total_tokens
|
||||||
type: object
|
type: object
|
||||||
securitySchemes:
|
securitySchemes:
|
||||||
admin:
|
bearer:
|
||||||
description: The bootstrap admin token
|
description: A personal API token, or the bootstrap admin token
|
||||||
scheme: bearer
|
scheme: bearer
|
||||||
type: http
|
type: http
|
||||||
|
session:
|
||||||
|
description: The session a browser sign-in opens
|
||||||
|
in: cookie
|
||||||
|
name: archie_session
|
||||||
|
type: apiKey
|
||||||
info:
|
info:
|
||||||
title: Archie
|
title: Archie
|
||||||
version: dev
|
version: dev
|
||||||
openapi: 3.1.0
|
openapi: 3.1.0
|
||||||
paths:
|
paths:
|
||||||
|
/api/account/passkeys:
|
||||||
|
get:
|
||||||
|
operationId: list-passkeys
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/GovernancePasskeysBody"
|
||||||
|
description: OK
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
summary: List your passkeys
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
|
/api/account/passkeys/begin:
|
||||||
|
post:
|
||||||
|
operationId: begin-passkey-registration
|
||||||
|
parameters:
|
||||||
|
- in: cookie
|
||||||
|
name: archie_session
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema: {}
|
||||||
|
description: OK
|
||||||
|
headers:
|
||||||
|
Cache-Control:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
Set-Cookie:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
summary: Start adding a passkey
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
|
/api/account/passkeys/finish:
|
||||||
|
post:
|
||||||
|
operationId: finish-passkey-registration
|
||||||
|
parameters:
|
||||||
|
- in: cookie
|
||||||
|
name: archie_session
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
- in: cookie
|
||||||
|
name: archie_passkey_registration
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
requestBody:
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/GovernancePasskeyFinishBody"
|
||||||
|
required: true
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/GovernanceUserBody"
|
||||||
|
description: OK
|
||||||
|
headers:
|
||||||
|
Cache-Control:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
Set-Cookie:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
summary: Finish adding a passkey
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
|
/api/account/passkeys/{id}:
|
||||||
|
delete:
|
||||||
|
operationId: delete-passkey
|
||||||
|
parameters:
|
||||||
|
- in: cookie
|
||||||
|
name: archie_session
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
- in: path
|
||||||
|
name: id
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
responses:
|
||||||
|
"204":
|
||||||
|
description: No Content
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
summary: Remove a passkey
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
|
/api/account/password:
|
||||||
|
post:
|
||||||
|
operationId: change-password
|
||||||
|
requestBody:
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ChangePasswordInputBody"
|
||||||
|
required: true
|
||||||
|
responses:
|
||||||
|
"204":
|
||||||
|
description: No Content
|
||||||
|
headers:
|
||||||
|
Cache-Control:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
Set-Cookie:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
summary: Change your password
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
|
/api/account/recovery:
|
||||||
|
post:
|
||||||
|
operationId: create-recovery-code
|
||||||
|
parameters:
|
||||||
|
- in: cookie
|
||||||
|
name: archie_session
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/RecoveryCodeReplyBody"
|
||||||
|
description: OK
|
||||||
|
headers:
|
||||||
|
Cache-Control:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
summary: Create a recovery code
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
|
/api/accounts:
|
||||||
|
post:
|
||||||
|
operationId: create-account
|
||||||
|
parameters:
|
||||||
|
- in: cookie
|
||||||
|
name: archie_session
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
requestBody:
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/GovernanceRegistration"
|
||||||
|
required: true
|
||||||
|
responses:
|
||||||
|
"201":
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/GovernanceUserBody"
|
||||||
|
description: Created
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
summary: Create an account
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
/api/admin/token:
|
/api/admin/token:
|
||||||
post:
|
post:
|
||||||
operationId: rotate-admin-token
|
operationId: rotate-admin-token
|
||||||
@@ -2230,6 +2696,290 @@ paths:
|
|||||||
summary: Approve or refuse an action as the bootstrap admin
|
summary: Approve or refuse an action as the bootstrap admin
|
||||||
tags:
|
tags:
|
||||||
- Approvals
|
- Approvals
|
||||||
|
/api/auth/login:
|
||||||
|
post:
|
||||||
|
operationId: sign-in
|
||||||
|
requestBody:
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/SignInInputBody"
|
||||||
|
required: true
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/GovernanceUserBody"
|
||||||
|
description: OK
|
||||||
|
headers:
|
||||||
|
Cache-Control:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
Set-Cookie:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
security:
|
||||||
|
- {}
|
||||||
|
summary: Sign in with email and password
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
|
/api/auth/logout:
|
||||||
|
post:
|
||||||
|
operationId: sign-out
|
||||||
|
parameters:
|
||||||
|
- in: cookie
|
||||||
|
name: archie_session
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
responses:
|
||||||
|
"204":
|
||||||
|
description: No Content
|
||||||
|
headers:
|
||||||
|
Cache-Control:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
Set-Cookie:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
security:
|
||||||
|
- {}
|
||||||
|
summary: Sign out
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
|
/api/auth/passkey/begin:
|
||||||
|
post:
|
||||||
|
operationId: begin-passkey-sign-in
|
||||||
|
parameters:
|
||||||
|
- in: cookie
|
||||||
|
name: archie_session
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema: {}
|
||||||
|
description: OK
|
||||||
|
headers:
|
||||||
|
Cache-Control:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
Set-Cookie:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
security:
|
||||||
|
- {}
|
||||||
|
summary: Start signing in with a passkey
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
|
/api/auth/passkey/finish:
|
||||||
|
post:
|
||||||
|
operationId: finish-passkey-sign-in
|
||||||
|
parameters:
|
||||||
|
- in: cookie
|
||||||
|
name: archie_passkey_login
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
requestBody:
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/GovernancePasskeyFinishBody"
|
||||||
|
required: true
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/GovernanceUserBody"
|
||||||
|
description: OK
|
||||||
|
headers:
|
||||||
|
Cache-Control:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
Set-Cookie:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
security:
|
||||||
|
- {}
|
||||||
|
summary: Finish signing in with a passkey
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
|
/api/auth/recover:
|
||||||
|
post:
|
||||||
|
operationId: recover-account
|
||||||
|
requestBody:
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/RecoverInputBody"
|
||||||
|
required: true
|
||||||
|
responses:
|
||||||
|
"204":
|
||||||
|
description: No Content
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
security:
|
||||||
|
- {}
|
||||||
|
summary: Reset a password with a recovery code
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
|
/api/auth/setup:
|
||||||
|
post:
|
||||||
|
operationId: set-up-account
|
||||||
|
requestBody:
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/GovernanceRegistration"
|
||||||
|
required: true
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/GovernanceUserBody"
|
||||||
|
description: OK
|
||||||
|
headers:
|
||||||
|
Cache-Control:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
Set-Cookie:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
security:
|
||||||
|
- {}
|
||||||
|
summary: Create the instance owner and sign in
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
|
/api/auth/status:
|
||||||
|
get:
|
||||||
|
operationId: get-auth-status
|
||||||
|
parameters:
|
||||||
|
- in: cookie
|
||||||
|
name: archie_session
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/GovernanceAuthStatusBody"
|
||||||
|
description: OK
|
||||||
|
headers:
|
||||||
|
Cache-Control:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
security:
|
||||||
|
- {}
|
||||||
|
summary: Report setup and who is signed in
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
|
/api/authentication:
|
||||||
|
get:
|
||||||
|
operationId: get-authentication
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/GovernanceAuthenticationSettings"
|
||||||
|
description: OK
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
summary: Get the authentication settings
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
|
put:
|
||||||
|
operationId: put-authentication
|
||||||
|
parameters:
|
||||||
|
- in: cookie
|
||||||
|
name: archie_session
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
requestBody:
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/AuthenticationInputBody"
|
||||||
|
required: true
|
||||||
|
responses:
|
||||||
|
"204":
|
||||||
|
description: No Content
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
summary: Change the authentication settings
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
|
/api/capabilities:
|
||||||
|
get:
|
||||||
|
operationId: get-capabilities
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/GovernanceCapabilitiesBody"
|
||||||
|
description: OK
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
summary: Report which dashboard sections this binary serves
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
/api/chat/sessions:
|
/api/chat/sessions:
|
||||||
get:
|
get:
|
||||||
operationId: list-chat-sessions
|
operationId: list-chat-sessions
|
||||||
@@ -3753,6 +4503,74 @@ paths:
|
|||||||
summary: Get the bootstrap values, which only the config file sets
|
summary: Get the bootstrap values, which only the config file sets
|
||||||
tags:
|
tags:
|
||||||
- System
|
- System
|
||||||
|
/api/tokens:
|
||||||
|
get:
|
||||||
|
operationId: list-personal-tokens
|
||||||
|
responses:
|
||||||
|
"200":
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/GovernanceTokensBody"
|
||||||
|
description: OK
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
summary: List your personal API tokens
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
|
post:
|
||||||
|
operationId: create-personal-token
|
||||||
|
requestBody:
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/CreateTokenInputBody"
|
||||||
|
required: true
|
||||||
|
responses:
|
||||||
|
"201":
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/GovernanceCreatedToken"
|
||||||
|
description: Created
|
||||||
|
headers:
|
||||||
|
Cache-Control:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
summary: Create a personal API token
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
|
/api/tokens/{id}:
|
||||||
|
delete:
|
||||||
|
operationId: revoke-personal-token
|
||||||
|
parameters:
|
||||||
|
- in: path
|
||||||
|
name: id
|
||||||
|
required: true
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
responses:
|
||||||
|
"204":
|
||||||
|
description: No Content
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
summary: Revoke a personal API token
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
/api/triggers:
|
/api/triggers:
|
||||||
get:
|
get:
|
||||||
operationId: list-triggers
|
operationId: list-triggers
|
||||||
@@ -3921,5 +4739,89 @@ paths:
|
|||||||
summary: Save a workflow document as its next version
|
summary: Save a workflow document as its next version
|
||||||
tags:
|
tags:
|
||||||
- Workflows
|
- Workflows
|
||||||
|
/oauth2/callback:
|
||||||
|
get:
|
||||||
|
operationId: finish-oidc-sign-in
|
||||||
|
parameters:
|
||||||
|
- explode: false
|
||||||
|
in: query
|
||||||
|
name: code
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
- explode: false
|
||||||
|
in: query
|
||||||
|
name: state
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
- explode: false
|
||||||
|
in: query
|
||||||
|
name: error
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
- in: cookie
|
||||||
|
name: archie_login_state
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
- in: cookie
|
||||||
|
name: archie_login_verifier
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
responses:
|
||||||
|
"303":
|
||||||
|
description: See Other
|
||||||
|
headers:
|
||||||
|
Cache-Control:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
Location:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
Set-Cookie:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
security:
|
||||||
|
- {}
|
||||||
|
summary: Complete the identity provider's sign-in
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
|
/oauth2/login:
|
||||||
|
get:
|
||||||
|
operationId: begin-oidc-sign-in
|
||||||
|
parameters:
|
||||||
|
- in: cookie
|
||||||
|
name: archie_session
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
responses:
|
||||||
|
"303":
|
||||||
|
description: See Other
|
||||||
|
headers:
|
||||||
|
Cache-Control:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
Location:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
Set-Cookie:
|
||||||
|
schema:
|
||||||
|
type: string
|
||||||
|
default:
|
||||||
|
content:
|
||||||
|
application/problem+json:
|
||||||
|
schema:
|
||||||
|
$ref: "#/components/schemas/ErrorModel"
|
||||||
|
description: Error
|
||||||
|
security:
|
||||||
|
- {}
|
||||||
|
summary: Send the browser to the identity provider
|
||||||
|
tags:
|
||||||
|
- Accounts
|
||||||
security:
|
security:
|
||||||
- admin: []
|
- session: []
|
||||||
|
- bearer: []
|
||||||
@@ -37,6 +37,7 @@ type apiModules struct {
|
|||||||
|
|
||||||
func (m apiModules) register(api huma.API) {
|
func (m apiModules) register(api huma.API) {
|
||||||
m.settings.Register(api)
|
m.settings.Register(api)
|
||||||
|
m.settings.RegisterAccounts(api)
|
||||||
m.conns.Register(api)
|
m.conns.Register(api)
|
||||||
m.system.Register(api)
|
m.system.Register(api)
|
||||||
m.tell.Register(api)
|
m.tell.Register(api)
|
||||||
@@ -54,9 +55,10 @@ func (m apiModules) register(api huma.API) {
|
|||||||
// registrations the server does, on modules with nothing behind them, so it
|
// registrations the server does, on modules with nothing behind them, so it
|
||||||
// needs no database.
|
// needs no database.
|
||||||
func Document() ([]byte, error) {
|
func Document() ([]byte, error) {
|
||||||
api := httpapi.New(http.NewServeMux(), buildinfo.Version, "")
|
settings := &governance.Module{}
|
||||||
|
api := httpapi.New(http.NewServeMux(), buildinfo.Version, settings.Authenticator(""))
|
||||||
apiModules{
|
apiModules{
|
||||||
settings: &governance.Module{}, conns: &connectors.Module{}, system: &system.Module{},
|
settings: settings, conns: &connectors.Module{}, system: &system.Module{},
|
||||||
tell: &deliveries.Module{}, allow: &approvals.Module{}, classes: &judgement.Classes{},
|
tell: &deliveries.Module{}, allow: &approvals.Module{}, classes: &judgement.Classes{},
|
||||||
policies: &judgement.Policies{}, hear: &events.Module{}, judge: &judgement.Module{},
|
policies: &judgement.Policies{}, hear: &events.Module{}, judge: &judgement.Module{},
|
||||||
engine: &runs.Engine{}, chat: &chat.Module{}, drafts: &drafts.Module{},
|
engine: &runs.Engine{}, chat: &chat.Module{}, drafts: &drafts.Module{},
|
||||||
|
|||||||
@@ -64,10 +64,10 @@ func Run(ctx context.Context, configPath string) error {
|
|||||||
checks.Register("database", db.PingContext)
|
checks.Register("database", db.PingContext)
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
checks.Routes(mux)
|
checks.Routes(mux)
|
||||||
api := httpapi.New(mux, buildinfo.Version, cfg.AdminTokenSHA256)
|
|
||||||
|
|
||||||
runtime.RegisterBuiltinClasses()
|
runtime.RegisterBuiltinClasses()
|
||||||
settings := governance.NewModule(db, log.With("module", "governance"), orgID)
|
settings := governance.NewModule(db, log.With("module", "governance"), orgID)
|
||||||
|
api := httpapi.New(mux, buildinfo.Version, settings.Authenticator(cfg.AdminTokenSHA256)) //nolint:contextcheck // the middleware derives from the request's context
|
||||||
|
|
||||||
conns, err := connectors.NewModule(db, log.With("module", "connectors"), orgID, connectors.Sealing{
|
conns, err := connectors.NewModule(db, log.With("module", "connectors"), orgID, connectors.Sealing{
|
||||||
Identity: cfg.AgeIdentity, Backups: cfg.AgeBackupRecipients,
|
Identity: cfg.AgeIdentity, Backups: cfg.AgeBackupRecipients,
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
package httpapi
|
package httpapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
"path"
|
"path"
|
||||||
"reflect"
|
"reflect"
|
||||||
@@ -11,14 +13,26 @@ import (
|
|||||||
|
|
||||||
"github.com/danielgtaylor/huma/v2"
|
"github.com/danielgtaylor/huma/v2"
|
||||||
"github.com/danielgtaylor/huma/v2/adapters/humago"
|
"github.com/danielgtaylor/huma/v2/adapters/humago"
|
||||||
|
|
||||||
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// DocumentPath is where the API serves its OpenAPI document, as .json and
|
// DocumentPath is where the API serves its OpenAPI document, as .json and
|
||||||
// .yaml.
|
// .yaml.
|
||||||
const DocumentPath = "/api/openapi"
|
const DocumentPath = "/api/openapi"
|
||||||
|
|
||||||
|
// SessionCookie is the cookie a browser's sign-in sets.
|
||||||
|
const SessionCookie = "archie_session"
|
||||||
|
|
||||||
|
// ErrUnauthenticated is what an Authenticator returns for a request whose
|
||||||
|
// credential is missing or not accepted.
|
||||||
|
var ErrUnauthenticated = errors.New("sign-in required or credentials not accepted")
|
||||||
|
|
||||||
|
// Authenticator resolves the credential a request presents. It returns ctx
|
||||||
|
// carrying who acts, and whether that caller administers
|
||||||
|
// the instance.
|
||||||
|
type Authenticator interface {
|
||||||
|
Authenticate(ctx context.Context, r *http.Request) (acting context.Context, admin bool, err error)
|
||||||
|
}
|
||||||
|
|
||||||
// Reply is an operation's output whose response body is T.
|
// Reply is an operation's output whose response body is T.
|
||||||
type Reply[T any] struct {
|
type Reply[T any] struct {
|
||||||
Body T
|
Body T
|
||||||
@@ -29,11 +43,50 @@ func OK[T any](v T) *Reply[T] {
|
|||||||
return &Reply[T]{Body: v}
|
return &Reply[T]{Body: v}
|
||||||
}
|
}
|
||||||
|
|
||||||
// New returns an API on mux whose every operation requires the bootstrap admin
|
type access int
|
||||||
// token, held only as its hash.
|
|
||||||
func New(mux *http.ServeMux, version, adminHash string) huma.API {
|
const (
|
||||||
|
accessAdmin access = iota
|
||||||
|
accessSignedIn
|
||||||
|
accessPublic
|
||||||
|
)
|
||||||
|
|
||||||
|
const accessKey = "archie-access"
|
||||||
|
|
||||||
|
// Public marks op as callable without a credential: signing in, for one.
|
||||||
|
func Public(op huma.Operation) huma.Operation {
|
||||||
|
op.Security = []map[string][]string{{}}
|
||||||
|
return withAccess(op, accessPublic)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SignedIn marks op as callable by any authenticated caller. Every other
|
||||||
|
// operation needs an instance administrator.
|
||||||
|
func SignedIn(op huma.Operation) huma.Operation {
|
||||||
|
return withAccess(op, accessSignedIn)
|
||||||
|
}
|
||||||
|
|
||||||
|
func withAccess(op huma.Operation, a access) huma.Operation {
|
||||||
|
if op.Metadata == nil {
|
||||||
|
op.Metadata = map[string]any{}
|
||||||
|
}
|
||||||
|
op.Metadata[accessKey] = a
|
||||||
|
return op
|
||||||
|
}
|
||||||
|
|
||||||
|
func accessOf(op *huma.Operation) access {
|
||||||
|
if op == nil {
|
||||||
|
return accessAdmin
|
||||||
|
}
|
||||||
|
a, _ := op.Metadata[accessKey].(access)
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
|
||||||
|
// New returns an API on mux whose operations authenticate through auth.
|
||||||
|
// Every unsafe request must also pass cross-origin protection, since a
|
||||||
|
// browser sends the session cookie with any request to this origin.
|
||||||
|
func New(mux *http.ServeMux, version string, auth Authenticator) huma.API {
|
||||||
api := humago.New(mux, config(version))
|
api := humago.New(mux, config(version))
|
||||||
api.UseMiddleware(admin(api, adminHash))
|
api.UseMiddleware(guard(api, auth, http.NewCrossOriginProtection()))
|
||||||
return api
|
return api
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,20 +99,39 @@ func config(version string) huma.Config {
|
|||||||
cfg.CreateHooks = nil
|
cfg.CreateHooks = nil
|
||||||
cfg.Components.Schemas = huma.NewMapRegistry("#/components/schemas/", schemaName)
|
cfg.Components.Schemas = huma.NewMapRegistry("#/components/schemas/", schemaName)
|
||||||
cfg.Components.SecuritySchemes = map[string]*huma.SecurityScheme{
|
cfg.Components.SecuritySchemes = map[string]*huma.SecurityScheme{
|
||||||
"admin": {Type: "http", Scheme: "bearer", Description: "The bootstrap admin token"},
|
"session": {Type: "apiKey", In: "cookie", Name: SessionCookie, Description: "The session a browser sign-in opens"},
|
||||||
|
"bearer": {Type: "http", Scheme: "bearer", Description: "A personal API token, or the bootstrap admin token"},
|
||||||
}
|
}
|
||||||
cfg.Security = []map[string][]string{{"admin": {}}}
|
cfg.Security = []map[string][]string{{"session": {}}, {"bearer": {}}}
|
||||||
return cfg
|
return cfg
|
||||||
}
|
}
|
||||||
|
|
||||||
func admin(api huma.API, hash string) func(huma.Context, func(huma.Context)) {
|
func guard(api huma.API, auth Authenticator, origins *http.CrossOriginProtection) func(huma.Context, func(huma.Context)) {
|
||||||
return func(ctx huma.Context, next func(huma.Context)) {
|
return func(ctx huma.Context, next func(huma.Context)) {
|
||||||
token, ok := strings.CutPrefix(ctx.Header("Authorization"), "Bearer ")
|
r, _ := humago.Unwrap(ctx)
|
||||||
if !ok || !httpjson.TokenMatches(strings.TrimSpace(token), hash) {
|
if err := origins.Check(r); err != nil {
|
||||||
_ = huma.WriteErr(api, ctx, http.StatusUnauthorized, "admin token required")
|
_ = huma.WriteErr(api, ctx, http.StatusForbidden, "cross-origin request refused")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
next(ctx)
|
need := accessOf(ctx.Operation())
|
||||||
|
if need == accessPublic {
|
||||||
|
next(ctx)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
acting, admin, err := auth.Authenticate(ctx.Context(), r)
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, ErrUnauthenticated):
|
||||||
|
ctx.SetHeader("Cache-Control", "no-store")
|
||||||
|
_ = huma.WriteErr(api, ctx, http.StatusUnauthorized, ErrUnauthenticated.Error())
|
||||||
|
return
|
||||||
|
case err != nil:
|
||||||
|
_ = huma.WriteErr(api, ctx, http.StatusServiceUnavailable, "authentication is unavailable")
|
||||||
|
return
|
||||||
|
case need == accessAdmin && !admin:
|
||||||
|
_ = huma.WriteErr(api, ctx, http.StatusForbidden, "instance administrator required")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next(huma.WithContext(ctx, acting))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,48 +2,73 @@ package httpapi
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/danielgtaylor/huma/v2"
|
"github.com/danielgtaylor/huma/v2"
|
||||||
|
|
||||||
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestEveryOperationRequiresTheAdminToken guards the bootstrap admin boundary:
|
// headerAuth admits the caller its X-Test-Caller header names.
|
||||||
// only a bearer token whose hash matches the configured one reaches an
|
type headerAuth struct{}
|
||||||
// operation, and an empty configured hash locks everyone out rather than
|
|
||||||
// letting everyone in.
|
func (headerAuth) Authenticate(ctx context.Context, r *http.Request) (context.Context, bool, error) {
|
||||||
func TestEveryOperationRequiresTheAdminToken(t *testing.T) {
|
switch r.Header.Get("X-Test-Caller") {
|
||||||
const token = "a-plainly-fake-admin-token" //nolint:gosec // test fixture, not a credential
|
case "admin":
|
||||||
|
return ctx, true, nil
|
||||||
|
case "person":
|
||||||
|
return ctx, false, nil
|
||||||
|
case "broken":
|
||||||
|
return nil, false, errors.New("database down")
|
||||||
|
default:
|
||||||
|
return nil, false, ErrUnauthenticated
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestOperationAccess guards the API's authentication boundary: public
|
||||||
|
// operations need no credential, every other operation needs one, only an
|
||||||
|
// instance administrator reaches an operation not marked otherwise, and a
|
||||||
|
// cross-origin browser request cannot use the session cookie to change
|
||||||
|
// anything.
|
||||||
|
func TestOperationAccess(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name, method, path, caller, fetchSite string
|
||||||
hash string
|
want int
|
||||||
header string
|
|
||||||
want int
|
|
||||||
}{
|
}{
|
||||||
{name: "matching token", hash: httpjson.TokenHash(token), header: "Bearer " + token, want: http.StatusOK},
|
{name: "public without a credential", method: http.MethodGet, path: "/public", want: http.StatusOK},
|
||||||
{name: "wrong token", hash: httpjson.TokenHash(token), header: "Bearer other", want: http.StatusUnauthorized},
|
{name: "public sign-in from this origin", method: http.MethodPost, path: "/public", fetchSite: "same-origin", want: http.StatusOK},
|
||||||
{name: "no token", hash: httpjson.TokenHash(token), header: "", want: http.StatusUnauthorized},
|
{name: "public sign-in from another origin", method: http.MethodPost, path: "/public", fetchSite: "cross-site", want: http.StatusForbidden},
|
||||||
{name: "not a bearer token", hash: httpjson.TokenHash(token), header: "Basic " + token, want: http.StatusUnauthorized},
|
{name: "signed-in without a credential", method: http.MethodGet, path: "/signed-in", want: http.StatusUnauthorized},
|
||||||
{name: "no configured hash locks everyone out", hash: "", header: "Bearer ", want: http.StatusUnauthorized},
|
{name: "signed-in as a person", method: http.MethodGet, path: "/signed-in", caller: "person", want: http.StatusOK},
|
||||||
|
{name: "admin without a credential", method: http.MethodGet, path: "/admin", want: http.StatusUnauthorized},
|
||||||
|
{name: "admin as a person", method: http.MethodGet, path: "/admin", caller: "person", want: http.StatusForbidden},
|
||||||
|
{name: "admin as the admin", method: http.MethodGet, path: "/admin", caller: "admin", want: http.StatusOK},
|
||||||
|
{name: "mutation from this origin", method: http.MethodPost, path: "/admin", caller: "admin", fetchSite: "same-origin", want: http.StatusOK},
|
||||||
|
{name: "mutation from another origin", method: http.MethodPost, path: "/admin", caller: "admin", fetchSite: "cross-site", want: http.StatusForbidden},
|
||||||
|
{name: "a failed lookup is not a refusal", method: http.MethodGet, path: "/admin", caller: "broken", want: http.StatusServiceUnavailable},
|
||||||
|
}
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
api := New(mux, "test", headerAuth{})
|
||||||
|
reached := func(context.Context, *struct{}) (*Reply[string], error) { return OK("reached"), nil }
|
||||||
|
for _, method := range []string{http.MethodGet, http.MethodPost} {
|
||||||
|
huma.Register(api, Public(huma.Operation{OperationID: "public-" + method, Method: method, Path: "/public"}), reached)
|
||||||
|
huma.Register(api, SignedIn(huma.Operation{OperationID: "signed-in-" + method, Method: method, Path: "/signed-in"}), reached)
|
||||||
|
huma.Register(api, huma.Operation{OperationID: "admin-" + method, Method: method, Path: "/admin"}, reached)
|
||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
mux := http.NewServeMux()
|
req := httptest.NewRequestWithContext(t.Context(), tt.method, tt.path, nil)
|
||||||
api := New(mux, "test", tt.hash)
|
if tt.caller != "" {
|
||||||
huma.Get(api, "/api/thing", func(context.Context, *struct{}) (*Reply[string], error) {
|
req.Header.Set("X-Test-Caller", tt.caller)
|
||||||
return OK("reached"), nil
|
}
|
||||||
})
|
if tt.fetchSite != "" {
|
||||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/thing", nil)
|
req.Header.Set("Sec-Fetch-Site", tt.fetchSite)
|
||||||
if tt.header != "" {
|
|
||||||
req.Header.Set("Authorization", tt.header)
|
|
||||||
}
|
}
|
||||||
rec := httptest.NewRecorder()
|
rec := httptest.NewRecorder()
|
||||||
mux.ServeHTTP(rec, req)
|
mux.ServeHTTP(rec, req)
|
||||||
if rec.Code != tt.want {
|
if rec.Code != tt.want {
|
||||||
t.Fatalf("status = %d, want %d", rec.Code, tt.want)
|
t.Fatalf("status = %d, want %d: %s", rec.Code, tt.want, rec.Body)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// Package dashboard serves the single binary's SPA: archie.html and its
|
// Package dashboard serves the single binary's SPA: index.html and its
|
||||||
// assets from the embedded build. Every other route belongs to a module.
|
// assets from the embedded build. Every other route belongs to a module.
|
||||||
package dashboard
|
package dashboard
|
||||||
|
|
||||||
@@ -10,7 +10,7 @@ import (
|
|||||||
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
||||||
)
|
)
|
||||||
|
|
||||||
const page = "archie.html"
|
const page = "index.html"
|
||||||
|
|
||||||
// Routes serves the SPA from dist on mux. A path under /api/ that no module
|
// Routes serves the SPA from dist on mux. A path under /api/ that no module
|
||||||
// claimed is a JSON 404, never the page. With no build embedded, the page
|
// claimed is a JSON 404, never the page. With no build embedded, the page
|
||||||
@@ -45,7 +45,7 @@ func handler(dist fs.FS) http.Handler {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
name := strings.TrimPrefix(r.URL.Path, "/")
|
name := strings.TrimPrefix(r.URL.Path, "/")
|
||||||
if name != "" && name != "index.html" && name != page {
|
if name != "" && name != page {
|
||||||
if info, err := fs.Stat(dist, name); err == nil && !info.IsDir() {
|
if info, err := fs.Stat(dist, name); err == nil && !info.IsDir() {
|
||||||
if strings.HasPrefix(name, "assets/") {
|
if strings.HasPrefix(name, "assets/") {
|
||||||
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
||||||
|
|||||||
@@ -0,0 +1,712 @@
|
|||||||
|
package governance
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json/jsontext"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/danielgtaylor/huma/v2"
|
||||||
|
|
||||||
|
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Cookie names beside httpapi.SessionCookie. The sign-in flow's cookies are
|
||||||
|
// scoped to the paths that read them.
|
||||||
|
const (
|
||||||
|
passkeyLoginCookie = "archie_passkey_login"
|
||||||
|
passkeyRegistrationCookie = "archie_passkey_registration"
|
||||||
|
loginStateCookie = "archie_login_state"
|
||||||
|
loginVerifierCookie = "archie_login_verifier"
|
||||||
|
|
||||||
|
passkeyCookiePath = "/api/"
|
||||||
|
loginCookiePath = "/oauth2"
|
||||||
|
passkeyCookieAge = 300
|
||||||
|
loginCookieAge = 600
|
||||||
|
|
||||||
|
maxTokenNameLength = 40
|
||||||
|
// personalTokenBindTimeout is under the dashboard's own request timeout.
|
||||||
|
personalTokenBindTimeout = 10 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
// client is the host a request reached, which decides whether a cookie must
|
||||||
|
// be Secure.
|
||||||
|
type client struct{ host string }
|
||||||
|
|
||||||
|
// Resolve reads the request's host. Huma calls it for every input that
|
||||||
|
// carries a client.
|
||||||
|
func (c *client) Resolve(ctx huma.Context) []error {
|
||||||
|
c.host = ctx.Host()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// cookie returns an HttpOnly, SameSite=Lax cookie, Secure unless the browser
|
||||||
|
// reached this host over loopback. A negative maxAge deletes it.
|
||||||
|
func (c *client) cookie(name, value, path string, maxAge int) http.Cookie {
|
||||||
|
return http.Cookie{ //nolint:gosec // G124: a fixed Secure would stop a browser on localhost signing in.
|
||||||
|
Name: name, Value: value, Path: path, MaxAge: maxAge,
|
||||||
|
HttpOnly: true, Secure: !loopback(c.host), SameSite: http.SameSiteLaxMode,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *client) session(s AccountSession) http.Cookie {
|
||||||
|
return c.cookie(httpapi.SessionCookie, s.Token, "/", int(time.Until(s.Expires).Seconds()))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *client) clear(name, path string) http.Cookie {
|
||||||
|
return c.cookie(name, "", path, -1)
|
||||||
|
}
|
||||||
|
|
||||||
|
type sessionInput struct {
|
||||||
|
Client client
|
||||||
|
Session string `cookie:"archie_session"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type cookieReply struct {
|
||||||
|
SetCookie []http.Cookie `header:"Set-Cookie"`
|
||||||
|
CacheControl string `header:"Cache-Control"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type userBody struct {
|
||||||
|
User Identity `json:"user"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type userReply struct {
|
||||||
|
SetCookie []http.Cookie `header:"Set-Cookie"`
|
||||||
|
CacheControl string `header:"Cache-Control"`
|
||||||
|
Body userBody
|
||||||
|
}
|
||||||
|
|
||||||
|
// RegisterAccounts adds sign-in and the signed-in person's account: password
|
||||||
|
// accounts, passkeys, recovery, OIDC, personal API tokens, the instance's
|
||||||
|
// authentication settings and what the dashboard can show.
|
||||||
|
func (m *Module) RegisterAccounts(api huma.API) {
|
||||||
|
tags := []string{"Accounts"}
|
||||||
|
public := func(id, method, path, summary string, status int) huma.Operation {
|
||||||
|
return httpapi.Public(huma.Operation{OperationID: id, Method: method, Path: path, Summary: summary, Tags: tags, DefaultStatus: status})
|
||||||
|
}
|
||||||
|
signedIn := func(id, method, path, summary string, status int) huma.Operation {
|
||||||
|
return httpapi.SignedIn(huma.Operation{OperationID: id, Method: method, Path: path, Summary: summary, Tags: tags, DefaultStatus: status})
|
||||||
|
}
|
||||||
|
admin := func(id, method, path, summary string, status int) huma.Operation {
|
||||||
|
return huma.Operation{OperationID: id, Method: method, Path: path, Summary: summary, Tags: tags, DefaultStatus: status}
|
||||||
|
}
|
||||||
|
huma.Register(api, public("get-auth-status", http.MethodGet, "/api/auth/status", "Report setup and who is signed in", 0), m.authStatus)
|
||||||
|
huma.Register(api, public("set-up-account", http.MethodPost, "/api/auth/setup", "Create the instance owner and sign in", 0), m.setUpAccount)
|
||||||
|
huma.Register(api, public("sign-in", http.MethodPost, "/api/auth/login", "Sign in with email and password", 0), m.signIn)
|
||||||
|
huma.Register(api, public("sign-out", http.MethodPost, "/api/auth/logout", "Sign out", http.StatusNoContent), m.signOut)
|
||||||
|
huma.Register(api, public("recover-account", http.MethodPost, "/api/auth/recover", "Reset a password with a recovery code", http.StatusNoContent), m.recoverAccount)
|
||||||
|
huma.Register(api, public("begin-passkey-sign-in", http.MethodPost, "/api/auth/passkey/begin", "Start signing in with a passkey", 0), m.beginPasskeySignIn)
|
||||||
|
huma.Register(api, public("finish-passkey-sign-in", http.MethodPost, "/api/auth/passkey/finish", "Finish signing in with a passkey", 0), m.finishPasskeySignIn)
|
||||||
|
huma.Register(api, public("begin-oidc-sign-in", http.MethodGet, "/oauth2/login", "Send the browser to the identity provider", http.StatusSeeOther), m.beginOIDC)
|
||||||
|
huma.Register(api, public("finish-oidc-sign-in", http.MethodGet, oidcCallbackPath, "Complete the identity provider's sign-in", http.StatusSeeOther), m.finishOIDC)
|
||||||
|
|
||||||
|
huma.Register(api, signedIn("change-password", http.MethodPost, "/api/account/password", "Change your password", http.StatusNoContent), m.changePassword)
|
||||||
|
huma.Register(api, signedIn("create-recovery-code", http.MethodPost, "/api/account/recovery", "Create a recovery code", 0), m.createRecoveryCode)
|
||||||
|
huma.Register(api, signedIn("list-passkeys", http.MethodGet, "/api/account/passkeys", "List your passkeys", 0), m.listPasskeys)
|
||||||
|
huma.Register(api, signedIn("begin-passkey-registration", http.MethodPost, "/api/account/passkeys/begin", "Start adding a passkey", 0), m.beginPasskeyRegistration)
|
||||||
|
huma.Register(api, signedIn("finish-passkey-registration", http.MethodPost, "/api/account/passkeys/finish", "Finish adding a passkey", 0), m.finishPasskeyRegistration)
|
||||||
|
huma.Register(api, signedIn("delete-passkey", http.MethodDelete, "/api/account/passkeys/{id}", "Remove a passkey", http.StatusNoContent), m.deletePasskey)
|
||||||
|
huma.Register(api, signedIn("list-personal-tokens", http.MethodGet, "/api/tokens", "List your personal API tokens", 0), m.listTokens)
|
||||||
|
huma.Register(api, signedIn("create-personal-token", http.MethodPost, "/api/tokens", "Create a personal API token", http.StatusCreated), m.createToken)
|
||||||
|
huma.Register(api, signedIn("revoke-personal-token", http.MethodDelete, "/api/tokens/{id}", "Revoke a personal API token", http.StatusNoContent), m.revokeToken)
|
||||||
|
huma.Register(api, signedIn("get-capabilities", http.MethodGet, "/api/capabilities", "Report which dashboard sections this binary serves", 0), m.capabilities)
|
||||||
|
|
||||||
|
huma.Register(api, admin("create-account", http.MethodPost, "/api/accounts", "Create an account", http.StatusCreated), m.createAccount)
|
||||||
|
huma.Register(api, admin("get-authentication", http.MethodGet, "/api/authentication", "Get the authentication settings", 0), m.getAuthentication)
|
||||||
|
huma.Register(api, admin("put-authentication", http.MethodPut, "/api/authentication", "Change the authentication settings", http.StatusNoContent), m.putAuthentication)
|
||||||
|
}
|
||||||
|
|
||||||
|
// accountError turns an account failure into the status a person can act on.
|
||||||
|
func (m *Module) accountError(ctx context.Context, err error) error {
|
||||||
|
switch {
|
||||||
|
case refused(err):
|
||||||
|
return huma.Error401Unauthorized(httpapi.ErrUnauthenticated.Error())
|
||||||
|
case errors.Is(err, ErrSetupComplete):
|
||||||
|
return huma.Error409Conflict(ErrSetupComplete.Error())
|
||||||
|
case errors.Is(err, ErrIdentityConflict):
|
||||||
|
return huma.Error409Conflict("An account already uses that email.")
|
||||||
|
case errors.Is(err, ErrInvalidIdentity):
|
||||||
|
return huma.Error400BadRequest("Enter a name, valid email, organisation name for setup, and an uncommon password of at least 15 characters (at most 1024 bytes).")
|
||||||
|
case errors.Is(err, ErrProviderUnavailable):
|
||||||
|
return huma.Error503ServiceUnavailable("The sign-in provider is unavailable. Try again shortly.")
|
||||||
|
default:
|
||||||
|
m.log.ErrorContext(ctx, "account operation failed", "err", err)
|
||||||
|
return huma.Error503ServiceUnavailable("Account service unavailable.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// person refuses a caller that is not a signed-in person: account security
|
||||||
|
// belongs to people, not to tokens acting for the system.
|
||||||
|
func person(ctx context.Context) error {
|
||||||
|
if p, ok := PrincipalFromContext(ctx); ok && p.Kind == KindUser {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return huma.Error401Unauthorized("sign-in required")
|
||||||
|
}
|
||||||
|
|
||||||
|
// requireFresh refuses an authenticator change unless the caller signed in
|
||||||
|
// within the last few minutes.
|
||||||
|
func (m *Module) requireFresh(ctx context.Context, session string) error {
|
||||||
|
if session == "" || m.RequireFreshAccountSession(ctx, session) != nil {
|
||||||
|
return huma.Error403Forbidden("Sign in again before changing account security.")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type authStatusBody struct {
|
||||||
|
SetupRequired bool `json:"setup_required"`
|
||||||
|
User *Identity `json:"user"`
|
||||||
|
OIDC bool `json:"oidc"`
|
||||||
|
PublicURL string `json:"public_url"`
|
||||||
|
Instance string `json:"instance"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type authStatusReply struct {
|
||||||
|
CacheControl string `header:"Cache-Control"`
|
||||||
|
Body authStatusBody
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) authStatus(ctx context.Context, in *sessionInput) (*authStatusReply, error) {
|
||||||
|
required, err := m.AccountSetupRequired(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
out := authStatusBody{SetupRequired: required, Instance: "archie"}
|
||||||
|
if in.Session != "" {
|
||||||
|
value, err := m.ResolveAccountSession(ctx, in.Session)
|
||||||
|
switch {
|
||||||
|
case err == nil && value.Kind == KindUser && value.CanAct():
|
||||||
|
out.User = &value
|
||||||
|
case err != nil && !refused(err):
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
settings, err := m.AuthenticationSettings(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
out.PublicURL = settings.PublicURL
|
||||||
|
out.OIDC = settings.PublicURL != "" && settings.OIDCIssuer != ""
|
||||||
|
return &authStatusReply{CacheControl: "no-store", Body: out}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type registration struct {
|
||||||
|
PublicURL string `json:"public_url,omitempty"`
|
||||||
|
WorkspaceName string `json:"workspace_name,omitempty"`
|
||||||
|
OrganisationName string `json:"organisation_name,omitempty"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
DisplayName string `json:"display_name"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
Role string `json:"role,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r registration) account() AccountRegistration {
|
||||||
|
return AccountRegistration(r)
|
||||||
|
}
|
||||||
|
|
||||||
|
type setUpInput struct {
|
||||||
|
Client client
|
||||||
|
Body registration
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) setUpAccount(ctx context.Context, in *setUpInput) (*userReply, error) {
|
||||||
|
if _, err := m.RegisterAccount(ctx, in.Body.account(), true); err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
return m.openSession(ctx, &in.Client, in.Body.Email, in.Body.Password)
|
||||||
|
}
|
||||||
|
|
||||||
|
type signInInput struct {
|
||||||
|
Client client
|
||||||
|
Body struct {
|
||||||
|
Email string `json:"email"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) signIn(ctx context.Context, in *signInInput) (*userReply, error) {
|
||||||
|
return m.openSession(ctx, &in.Client, in.Body.Email, in.Body.Password)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) openSession(ctx context.Context, c *client, email, password string) (*userReply, error) {
|
||||||
|
value, err := m.SignInAccount(ctx, email, password)
|
||||||
|
if err != nil {
|
||||||
|
m.log.InfoContext(ctx, "account sign-in refused")
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
m.log.InfoContext(ctx, "account signed in", "identity", value.Identity.ID)
|
||||||
|
return &userReply{SetCookie: []http.Cookie{c.session(value)}, CacheControl: "no-store", Body: userBody{User: value.Identity}}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) signOut(ctx context.Context, in *sessionInput) (*cookieReply, error) {
|
||||||
|
if in.Session != "" {
|
||||||
|
if err := m.SignOutAccount(ctx, in.Session); err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return &cookieReply{SetCookie: []http.Cookie{in.Client.clear(httpapi.SessionCookie, "/")}, CacheControl: "no-store"}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type recoverInput struct {
|
||||||
|
Body struct {
|
||||||
|
Email string `json:"email"`
|
||||||
|
Code string `json:"code"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) recoverAccount(ctx context.Context, in *recoverInput) (*struct{}, error) {
|
||||||
|
if err := m.RecoverAccount(ctx, in.Body.Email, in.Body.Code, in.Body.Password); err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type changePasswordInput struct {
|
||||||
|
Client client
|
||||||
|
Body struct {
|
||||||
|
Current string `json:"current_password"`
|
||||||
|
New string `json:"new_password"`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// changePassword revokes every session, so the browser's cookie goes too.
|
||||||
|
func (m *Module) changePassword(ctx context.Context, in *changePasswordInput) (*cookieReply, error) {
|
||||||
|
if err := person(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := m.ChangeAccountPassword(ctx, in.Body.Current, in.Body.New); err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
return &cookieReply{SetCookie: []http.Cookie{in.Client.clear(httpapi.SessionCookie, "/")}, CacheControl: "no-store"}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type recoveryCodeReply struct {
|
||||||
|
CacheControl string `header:"Cache-Control"`
|
||||||
|
Body struct {
|
||||||
|
Code string `json:"code"`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) createRecoveryCode(ctx context.Context, in *sessionInput) (*recoveryCodeReply, error) {
|
||||||
|
if err := person(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := m.requireFresh(ctx, in.Session); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
code, err := m.CreateAccountRecovery(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
out := &recoveryCodeReply{CacheControl: "no-store"}
|
||||||
|
out.Body.Code = code
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type createAccountInput struct {
|
||||||
|
Session string `cookie:"archie_session"`
|
||||||
|
Body registration
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) createAccount(ctx context.Context, in *createAccountInput) (*httpapi.Reply[userBody], error) {
|
||||||
|
if err := m.requireFresh(ctx, in.Session); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
value, err := m.RegisterAccount(ctx, in.Body.account(), false)
|
||||||
|
if err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
return httpapi.OK(userBody{User: value}), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) getAuthentication(ctx context.Context, _ *struct{}) (*httpapi.Reply[AuthenticationSettings], error) {
|
||||||
|
value, err := m.AuthenticationSettings(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
return httpapi.OK(value), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type authenticationInput struct {
|
||||||
|
Session string `cookie:"archie_session"`
|
||||||
|
Body struct {
|
||||||
|
PublicURL string `json:"public_url"`
|
||||||
|
OIDCIssuer string `json:"oidc_issuer,omitempty"`
|
||||||
|
OIDCAudience string `json:"oidc_audience,omitempty"`
|
||||||
|
OIDCClientID string `json:"oidc_client_id,omitempty"`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) putAuthentication(ctx context.Context, in *authenticationInput) (*struct{}, error) {
|
||||||
|
if err := m.requireFresh(ctx, in.Session); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
err := m.SaveAuthenticationSettings(ctx, AuthenticationSettings(in.Body))
|
||||||
|
if errors.Is(err, ErrInvalidIdentity) {
|
||||||
|
return nil, huma.Error400BadRequest("Use a valid instance origin and complete OIDC settings. Remove enrolled passkeys before changing the instance URL.")
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type passkeyOptionsReply struct {
|
||||||
|
SetCookie []http.Cookie `header:"Set-Cookie"`
|
||||||
|
CacheControl string `header:"Cache-Control"`
|
||||||
|
Body jsontext.Value
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) beginPasskeySignIn(ctx context.Context, in *sessionInput) (*passkeyOptionsReply, error) {
|
||||||
|
return m.beginPasskey(ctx, &in.Client, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) beginPasskeyRegistration(ctx context.Context, in *sessionInput) (*passkeyOptionsReply, error) {
|
||||||
|
if err := person(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := m.requireFresh(ctx, in.Session); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return m.beginPasskey(ctx, &in.Client, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func passkeyCookie(registration bool) string {
|
||||||
|
if registration {
|
||||||
|
return passkeyRegistrationCookie
|
||||||
|
}
|
||||||
|
return passkeyLoginCookie
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) beginPasskey(ctx context.Context, c *client, registration bool) (*passkeyOptionsReply, error) {
|
||||||
|
value, err := m.BeginPasskey(ctx, registration)
|
||||||
|
if err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
return &passkeyOptionsReply{
|
||||||
|
SetCookie: []http.Cookie{c.cookie(passkeyCookie(registration), value.Token, passkeyCookiePath, passkeyCookieAge)},
|
||||||
|
CacheControl: "no-store",
|
||||||
|
Body: jsontext.Value(value.Options),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type passkeyFinishBody struct {
|
||||||
|
Credential jsontext.Value `json:"credential"`
|
||||||
|
Name string `json:"name,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type passkeySignInInput struct {
|
||||||
|
Client client
|
||||||
|
Ceremony string `cookie:"archie_passkey_login"`
|
||||||
|
Body passkeyFinishBody
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) finishPasskeySignIn(ctx context.Context, in *passkeySignInInput) (*userReply, error) {
|
||||||
|
value, err := m.finishPasskey(ctx, in.Ceremony, in.Body, false)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &userReply{
|
||||||
|
SetCookie: []http.Cookie{in.Client.clear(passkeyLoginCookie, passkeyCookiePath), in.Client.session(value)},
|
||||||
|
CacheControl: "no-store",
|
||||||
|
Body: userBody{User: value.Identity},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type passkeyRegistrationInput struct {
|
||||||
|
Client client
|
||||||
|
Session string `cookie:"archie_session"`
|
||||||
|
Ceremony string `cookie:"archie_passkey_registration"`
|
||||||
|
Body passkeyFinishBody
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) finishPasskeyRegistration(ctx context.Context, in *passkeyRegistrationInput) (*userReply, error) {
|
||||||
|
if err := person(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := m.requireFresh(ctx, in.Session); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
value, err := m.finishPasskey(ctx, in.Ceremony, in.Body, true)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &userReply{
|
||||||
|
SetCookie: []http.Cookie{in.Client.clear(passkeyRegistrationCookie, passkeyCookiePath)},
|
||||||
|
CacheControl: "no-store",
|
||||||
|
Body: userBody{User: value.Identity},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) finishPasskey(ctx context.Context, ceremony string, body passkeyFinishBody, registration bool) (AccountSession, error) {
|
||||||
|
if ceremony == "" {
|
||||||
|
return AccountSession{}, huma.Error401Unauthorized("passkey request expired")
|
||||||
|
}
|
||||||
|
value, err := m.FinishPasskey(ctx, ceremony, body.Credential, registration, body.Name)
|
||||||
|
if err != nil {
|
||||||
|
return AccountSession{}, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
return value, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type passkeysBody struct {
|
||||||
|
Passkeys []Passkey `json:"passkeys"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) listPasskeys(ctx context.Context, _ *struct{}) (*httpapi.Reply[passkeysBody], error) {
|
||||||
|
if err := person(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
values, err := m.ListPasskeys(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
if values == nil {
|
||||||
|
values = []Passkey{}
|
||||||
|
}
|
||||||
|
return httpapi.OK(passkeysBody{Passkeys: values}), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type deletePasskeyInput struct {
|
||||||
|
Session string `cookie:"archie_session"`
|
||||||
|
ID string `path:"id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) deletePasskey(ctx context.Context, in *deletePasskeyInput) (*struct{}, error) {
|
||||||
|
if err := person(ctx); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := m.requireFresh(ctx, in.Session); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := m.DeletePasskey(ctx, in.ID); err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// tokenOwner reports whether the caller is a person who can hold personal
|
||||||
|
// tokens; the bootstrap admin token acts as the system and cannot.
|
||||||
|
func tokenOwner(ctx context.Context) bool {
|
||||||
|
p, ok := PrincipalFromContext(ctx)
|
||||||
|
return ok && p.IdentityID != "" && p.IdentityID != SystemID
|
||||||
|
}
|
||||||
|
|
||||||
|
type tokensBody struct {
|
||||||
|
Tokens []PersonalToken `json:"tokens"`
|
||||||
|
Available bool `json:"available"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) listTokens(ctx context.Context, _ *struct{}) (*httpapi.Reply[tokensBody], error) {
|
||||||
|
if !tokenOwner(ctx) {
|
||||||
|
return httpapi.OK(tokensBody{Tokens: []PersonalToken{}}), nil
|
||||||
|
}
|
||||||
|
tokens, err := m.ListPersonalTokens(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
if tokens == nil {
|
||||||
|
tokens = []PersonalToken{}
|
||||||
|
}
|
||||||
|
return httpapi.OK(tokensBody{Tokens: tokens, Available: true}), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type createTokenInput struct {
|
||||||
|
Body struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Days int `json:"days,omitempty"`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type createdToken struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Token string `json:"token"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type createTokenReply struct {
|
||||||
|
CacheControl string `header:"Cache-Control"`
|
||||||
|
Body createdToken
|
||||||
|
}
|
||||||
|
|
||||||
|
// createToken makes the token here and stores only its hash; the response is
|
||||||
|
// the one time the token is shown.
|
||||||
|
func (m *Module) createToken(ctx context.Context, in *createTokenInput) (*createTokenReply, error) {
|
||||||
|
if !tokenOwner(ctx) {
|
||||||
|
return nil, huma.Error403Forbidden("Personal tokens need a signed-in person.")
|
||||||
|
}
|
||||||
|
name := strings.TrimSpace(in.Body.Name)
|
||||||
|
if name == "" || utf8.RuneCountInString(name) > maxTokenNameLength {
|
||||||
|
return nil, huma.Error400BadRequest("Name a token in up to 40 characters.")
|
||||||
|
}
|
||||||
|
var expiresAt *time.Time
|
||||||
|
switch in.Body.Days {
|
||||||
|
case 0:
|
||||||
|
case 7, 30, 90:
|
||||||
|
t := time.Now().UTC().AddDate(0, 0, in.Body.Days)
|
||||||
|
expiresAt = &t
|
||||||
|
default:
|
||||||
|
return nil, huma.Error400BadRequest("Lifetime is 7, 30 or 90 days, or none.")
|
||||||
|
}
|
||||||
|
raw, subject, err := NewPersonalToken()
|
||||||
|
if err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
if err := m.addPersonalToken(ctx, subject, name, expiresAt); err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
return &createTokenReply{CacheControl: "no-store", Body: createdToken{ID: subject.Subject, Token: raw}}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// addPersonalToken binds the token under its own deadline. The token is
|
||||||
|
// shown only once, so a bind that fails may still have committed: revoke it,
|
||||||
|
// detached from the request that is over, rather than leave a token nobody
|
||||||
|
// holds.
|
||||||
|
func (m *Module) addPersonalToken(ctx context.Context, subject Subject, name string, expiresAt *time.Time) error {
|
||||||
|
bindCtx, cancel := context.WithTimeout(ctx, personalTokenBindTimeout)
|
||||||
|
defer cancel()
|
||||||
|
err := m.AddPersonalToken(bindCtx, subject, name, expiresAt)
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
revokeCtx, revokeCancel := context.WithTimeout(context.WithoutCancel(ctx), personalTokenBindTimeout)
|
||||||
|
defer revokeCancel()
|
||||||
|
if revokeErr := m.RevokePersonalToken(revokeCtx, subject.Subject); revokeErr != nil && !errors.Is(revokeErr, ErrIdentityNotFound) {
|
||||||
|
return errors.Join(err, fmt.Errorf("revoke unconfirmed token: %w", revokeErr))
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
type revokeTokenInput struct {
|
||||||
|
ID string `path:"id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Module) revokeToken(ctx context.Context, in *revokeTokenInput) (*struct{}, error) {
|
||||||
|
if !tokenOwner(ctx) {
|
||||||
|
return nil, huma.Error403Forbidden("Personal tokens need a signed-in person.")
|
||||||
|
}
|
||||||
|
if err := m.RevokePersonalToken(ctx, in.ID); err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type capabilitiesBody struct {
|
||||||
|
Sections map[string]bool `json:"sections"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// capabilities reports the dashboard sections this binary serves. The
|
||||||
|
// sections below have no backend here yet, so the dashboard hides them;
|
||||||
|
// settings is the instance area, which only an instance administrator
|
||||||
|
// operates.
|
||||||
|
func (m *Module) capabilities(ctx context.Context, _ *struct{}) (*httpapi.Reply[capabilitiesBody], error) {
|
||||||
|
p, _ := PrincipalFromContext(ctx)
|
||||||
|
sections := map[string]bool{"settings": p.InstanceAdmin()}
|
||||||
|
for _, name := range []string{
|
||||||
|
"chat", "logs", "skills", "curators", "channels", "captures", "mappings", "bindings", "workflows",
|
||||||
|
"org_members", "org_agents", "org_policies", "org_denials", "org_audit", "org_usage", "org_config",
|
||||||
|
} {
|
||||||
|
sections[name] = false
|
||||||
|
}
|
||||||
|
return httpapi.OK(capabilitiesBody{Sections: sections}), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type redirectReply struct {
|
||||||
|
Location string `header:"Location"`
|
||||||
|
SetCookie []http.Cookie `header:"Set-Cookie"`
|
||||||
|
CacheControl string `header:"Cache-Control"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// beginOIDC sends a browser to the provider, keeping the state and PKCE
|
||||||
|
// verifier the callback needs in cookies scoped to the callback path.
|
||||||
|
func (m *Module) beginOIDC(ctx context.Context, in *sessionInput) (*redirectReply, error) {
|
||||||
|
flow, err := m.oidc.flow(ctx, m)
|
||||||
|
if errors.Is(err, ErrNoCredential) {
|
||||||
|
return nil, huma.Error404NotFound("no identity provider is configured")
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
state, err := randomState()
|
||||||
|
if err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
target, verifier, err := flow.AuthCodeURL(ctx, state)
|
||||||
|
if err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
return &redirectReply{
|
||||||
|
Location: target,
|
||||||
|
SetCookie: []http.Cookie{
|
||||||
|
in.Client.cookie(loginStateCookie, state, loginCookiePath, loginCookieAge),
|
||||||
|
in.Client.cookie(loginVerifierCookie, verifier, loginCookiePath, loginCookieAge),
|
||||||
|
},
|
||||||
|
CacheControl: "no-store",
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type oidcCallbackInput struct {
|
||||||
|
Client client
|
||||||
|
Code string `query:"code"`
|
||||||
|
State string `query:"state"`
|
||||||
|
ProviderError string `query:"error"`
|
||||||
|
WantState string `cookie:"archie_login_state"`
|
||||||
|
Verifier string `cookie:"archie_login_verifier"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// finishOIDC checks the state it issued, exchanges the code with the PKCE
|
||||||
|
// verifier it issued, and opens a local session no longer than the
|
||||||
|
// provider's.
|
||||||
|
func (m *Module) finishOIDC(ctx context.Context, in *oidcCallbackInput) (*redirectReply, error) {
|
||||||
|
if in.ProviderError != "" {
|
||||||
|
return nil, m.accountError(ctx, fmt.Errorf("%w: provider returned %s", ErrCredentialRejected, in.ProviderError))
|
||||||
|
}
|
||||||
|
if in.WantState == "" || !sameToken(in.WantState, in.State) || in.Verifier == "" {
|
||||||
|
return nil, m.accountError(ctx, fmt.Errorf("%w: sign-in state did not match", ErrCredentialRejected))
|
||||||
|
}
|
||||||
|
flow, err := m.oidc.flow(ctx, m)
|
||||||
|
if err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
session, err := flow.Exchange(ctx, in.Code, in.Verifier)
|
||||||
|
if err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
value, err := ResolveCredential(ctx, m, session.Credential)
|
||||||
|
if err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
p, err := m.PrincipalFor(ctx, value.ID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
local, err := m.OpenAccountSession(WithPrincipal(ctx, p), session.Expires)
|
||||||
|
if err != nil {
|
||||||
|
return nil, m.accountError(ctx, err)
|
||||||
|
}
|
||||||
|
m.log.InfoContext(ctx, "account signed in through the identity provider", "identity", value.ID)
|
||||||
|
return &redirectReply{
|
||||||
|
Location: "/",
|
||||||
|
SetCookie: []http.Cookie{
|
||||||
|
in.Client.clear(loginStateCookie, loginCookiePath),
|
||||||
|
in.Client.clear(loginVerifierCookie, loginCookiePath),
|
||||||
|
in.Client.session(local),
|
||||||
|
},
|
||||||
|
CacheControl: "no-store",
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func randomState() (string, error) {
|
||||||
|
raw := make([]byte, 32)
|
||||||
|
if _, err := rand.Read(raw); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return base64.RawURLEncoding.EncodeToString(raw), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
package governance
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/subtle"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||||
|
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
||||||
|
)
|
||||||
|
|
||||||
|
// credentials is what authenticating a request reads.
|
||||||
|
type credentials interface {
|
||||||
|
ResolveAccountSession(context.Context, string) (Identity, error)
|
||||||
|
ResolveSubject(context.Context, Subject) (Identity, error)
|
||||||
|
PersonalTokenOf(context.Context, Subject) (PersonalToken, error)
|
||||||
|
TouchPersonalToken(context.Context, Subject, time.Time) error
|
||||||
|
PrincipalFor(context.Context, IdentityID) (Principal, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// authenticator admits, in order, a browser session cookie, a personal API
|
||||||
|
// token, or the bootstrap admin token, which is held only as its hash.
|
||||||
|
type authenticator struct {
|
||||||
|
creds credentials
|
||||||
|
adminHash string
|
||||||
|
now func() time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// Authenticator returns the API's authenticator over the module's accounts
|
||||||
|
// and personal tokens, with adminHash the bootstrap admin token's hash.
|
||||||
|
func (m *Module) Authenticator(adminHash string) httpapi.Authenticator {
|
||||||
|
return authenticator{creds: m, adminHash: adminHash, now: time.Now}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a authenticator) Authenticate(ctx context.Context, r *http.Request) (context.Context, bool, error) {
|
||||||
|
if c, err := r.Cookie(httpapi.SessionCookie); err == nil {
|
||||||
|
value, err := a.creds.ResolveAccountSession(ctx, c.Value)
|
||||||
|
return a.acting(ctx, value, err)
|
||||||
|
}
|
||||||
|
token, ok := bearer(r)
|
||||||
|
if !ok {
|
||||||
|
return nil, false, httpapi.ErrUnauthenticated
|
||||||
|
}
|
||||||
|
if subject, ok := PersonalTokenSubject(token); ok {
|
||||||
|
if err := UsePersonalToken(ctx, a.creds, subject, a.now()); err != nil {
|
||||||
|
return a.acting(ctx, Identity{}, err)
|
||||||
|
}
|
||||||
|
value, err := a.creds.ResolveSubject(ctx, subject)
|
||||||
|
return a.acting(ctx, value, err)
|
||||||
|
}
|
||||||
|
if httpjson.TokenMatches(token, a.adminHash) {
|
||||||
|
return actingAs(ctx, SharedTokenOwner()), true, nil
|
||||||
|
}
|
||||||
|
return nil, false, httpapi.ErrUnauthenticated
|
||||||
|
}
|
||||||
|
|
||||||
|
// acting is the principal an identity resolved from a credential acts as.
|
||||||
|
func (a authenticator) acting(ctx context.Context, value Identity, err error) (context.Context, bool, error) {
|
||||||
|
if err == nil && !value.CanAct() {
|
||||||
|
err = ErrIdentityInactive
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
if refused(err) {
|
||||||
|
return nil, false, httpapi.ErrUnauthenticated
|
||||||
|
}
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
p, err := a.creds.PrincipalFor(ctx, value.ID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
p.Kind = value.Kind
|
||||||
|
return actingAs(ctx, p), p.InstanceAdmin(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func actingAs(ctx context.Context, p Principal) context.Context {
|
||||||
|
return WithOrg(WithPrincipal(ctx, p), p.Org)
|
||||||
|
}
|
||||||
|
|
||||||
|
// refused reports whether err says the credential was not accepted, as
|
||||||
|
// opposed to the lookup failing.
|
||||||
|
func refused(err error) bool {
|
||||||
|
for _, target := range []error{ErrNoCredential, ErrCredentialRejected, ErrIdentityNotFound, ErrIdentityInactive, ErrSubjectUnbound} {
|
||||||
|
if errors.Is(err, target) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func bearer(r *http.Request) (string, bool) {
|
||||||
|
const prefix = "Bearer "
|
||||||
|
header := r.Header.Get("Authorization")
|
||||||
|
if len(header) <= len(prefix) || !strings.EqualFold(header[:len(prefix)], prefix) {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
token := strings.TrimSpace(header[len(prefix):])
|
||||||
|
return token, token != ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// loopback reports whether host, as a request's Host header gives it, names
|
||||||
|
// this machine. Browsers send a Secure cookie only over HTTPS, except to
|
||||||
|
// localhost.
|
||||||
|
func loopback(host string) bool {
|
||||||
|
if name, _, err := net.SplitHostPort(host); err == nil {
|
||||||
|
host = name
|
||||||
|
}
|
||||||
|
host = strings.Trim(host, "[]")
|
||||||
|
if strings.EqualFold(host, "localhost") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
ip := net.ParseIP(host)
|
||||||
|
return ip != nil && ip.IsLoopback()
|
||||||
|
}
|
||||||
|
|
||||||
|
func sameToken(got, want string) bool {
|
||||||
|
return subtle.ConstantTimeCompare([]byte(got), []byte(want)) == 1
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
package governance
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||||
|
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fakeCredentials holds sessions and personal tokens by their raw value.
|
||||||
|
type fakeCredentials struct {
|
||||||
|
sessions map[string]Identity
|
||||||
|
tokens map[Subject]PersonalToken
|
||||||
|
subjects map[Subject]Identity
|
||||||
|
principals map[IdentityID]Principal
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f fakeCredentials) ResolveAccountSession(_ context.Context, token string) (Identity, error) {
|
||||||
|
if token == "broken" {
|
||||||
|
return Identity{}, errors.New("database down")
|
||||||
|
}
|
||||||
|
if v, ok := f.sessions[token]; ok {
|
||||||
|
return v, nil
|
||||||
|
}
|
||||||
|
return Identity{}, ErrIdentityNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f fakeCredentials) ResolveSubject(_ context.Context, s Subject) (Identity, error) {
|
||||||
|
if v, ok := f.subjects[s]; ok {
|
||||||
|
return v, nil
|
||||||
|
}
|
||||||
|
return Identity{}, ErrIdentityNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f fakeCredentials) PersonalTokenOf(_ context.Context, s Subject) (PersonalToken, error) {
|
||||||
|
if v, ok := f.tokens[s]; ok {
|
||||||
|
return v, nil
|
||||||
|
}
|
||||||
|
return PersonalToken{}, ErrIdentityNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fakeCredentials) TouchPersonalToken(context.Context, Subject, time.Time) error { return nil }
|
||||||
|
|
||||||
|
func (f fakeCredentials) PrincipalFor(_ context.Context, id IdentityID) (Principal, error) {
|
||||||
|
return f.principals[id], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAuthenticateRequest guards the API's credential check: a session
|
||||||
|
// cookie or personal token acts as its own identity with that identity's
|
||||||
|
// role, the bootstrap admin token acts as the instance owner, and a
|
||||||
|
// tampered, expired or inactive credential is refused rather than acting as
|
||||||
|
// anyone.
|
||||||
|
func TestAuthenticateRequest(t *testing.T) {
|
||||||
|
const admin = "a-plainly-fake-admin-token" //nolint:gosec // test fixture, not a credential
|
||||||
|
now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||||
|
past := now.Add(-time.Hour)
|
||||||
|
owner := Identity{ID: "owner", Kind: KindUser, Lifecycle: LifecycleActive}
|
||||||
|
viewer := Identity{ID: "viewer", Kind: KindUser, Lifecycle: LifecycleActive}
|
||||||
|
suspended := Identity{ID: "suspended", Kind: KindUser, Lifecycle: LifecycleSuspended}
|
||||||
|
ownerToken, ownerSubject := personalToken(t)
|
||||||
|
viewerToken, viewerSubject := personalToken(t)
|
||||||
|
expiredToken, expiredSubject := personalToken(t)
|
||||||
|
creds := fakeCredentials{
|
||||||
|
sessions: map[string]Identity{"owner-session": owner, "viewer-session": viewer, "suspended-session": suspended},
|
||||||
|
tokens: map[Subject]PersonalToken{
|
||||||
|
ownerSubject: {}, viewerSubject: {}, expiredSubject: {ExpiresAt: &past},
|
||||||
|
},
|
||||||
|
subjects: map[Subject]Identity{ownerSubject: owner, viewerSubject: viewer, expiredSubject: owner},
|
||||||
|
principals: map[IdentityID]Principal{
|
||||||
|
"owner": {IdentityID: "owner", Org: DefaultOrgID, Memberships: []Membership{{IdentityID: "owner", OrgID: DefaultOrgID, Role: RoleOwner}}},
|
||||||
|
"viewer": {IdentityID: "viewer", Org: DefaultOrgID, Memberships: []Membership{{IdentityID: "viewer", OrgID: DefaultOrgID, Role: RoleViewer}}},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
tests := []struct {
|
||||||
|
name, cookie, bearer, adminHash string
|
||||||
|
wantErr error
|
||||||
|
wantID IdentityID
|
||||||
|
wantRole Role
|
||||||
|
wantAdmin bool
|
||||||
|
}{
|
||||||
|
{name: "no credential", wantErr: httpapi.ErrUnauthenticated},
|
||||||
|
{name: "owner session", cookie: "owner-session", wantID: "owner", wantRole: RoleOwner, wantAdmin: true},
|
||||||
|
{name: "viewer session", cookie: "viewer-session", wantID: "viewer", wantRole: RoleViewer},
|
||||||
|
{name: "tampered session", cookie: "owner-sessiom", wantErr: httpapi.ErrUnauthenticated},
|
||||||
|
{name: "suspended identity's session", cookie: "suspended-session", wantErr: httpapi.ErrUnauthenticated},
|
||||||
|
{name: "a failed session lookup is not a refusal", cookie: "broken", wantErr: errors.New("any")},
|
||||||
|
{name: "owner's personal token", bearer: ownerToken, wantID: "owner", wantRole: RoleOwner, wantAdmin: true},
|
||||||
|
{name: "viewer's personal token keeps the viewer role", bearer: viewerToken, wantID: "viewer", wantRole: RoleViewer},
|
||||||
|
{name: "expired personal token", bearer: expiredToken, wantErr: httpapi.ErrUnauthenticated},
|
||||||
|
{name: "unknown personal token", bearer: "archie_pat_00", wantErr: httpapi.ErrUnauthenticated}, //nolint:gosec // G101: a token no store holds, which must be refused.
|
||||||
|
{name: "admin token", bearer: admin, adminHash: httpjson.TokenHash(admin), wantID: SystemID, wantRole: RoleOwner, wantAdmin: true},
|
||||||
|
{name: "wrong admin token", bearer: "other", adminHash: httpjson.TokenHash(admin), wantErr: httpapi.ErrUnauthenticated},
|
||||||
|
{name: "no admin hash locks the admin token out", bearer: admin, wantErr: httpapi.ErrUnauthenticated},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
auth := authenticator{creds: creds, adminHash: tt.adminHash, now: func() time.Time { return now }}
|
||||||
|
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/thing", nil)
|
||||||
|
if tt.cookie != "" {
|
||||||
|
req.AddCookie(&http.Cookie{Name: httpapi.SessionCookie, Value: tt.cookie}) //nolint:gosec // G124: a request cookie; attributes are the server's to set.
|
||||||
|
}
|
||||||
|
if tt.bearer != "" {
|
||||||
|
req.Header.Set("Authorization", "Bearer "+tt.bearer)
|
||||||
|
}
|
||||||
|
acting, admin, err := auth.Authenticate(req.Context(), req)
|
||||||
|
if tt.wantErr != nil {
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("authenticated, want refused")
|
||||||
|
}
|
||||||
|
if errors.Is(tt.wantErr, httpapi.ErrUnauthenticated) != errors.Is(err, httpapi.ErrUnauthenticated) {
|
||||||
|
t.Fatalf("err = %v, want %v", err, tt.wantErr)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Authenticate: %v", err)
|
||||||
|
}
|
||||||
|
p, ok := PrincipalFromContext(acting)
|
||||||
|
if !ok || p.IdentityID != tt.wantID || p.Role("") != tt.wantRole || admin != tt.wantAdmin {
|
||||||
|
t.Fatalf("acts as %s role %q admin %v, want %s role %q admin %v", p.IdentityID, p.Role(""), admin, tt.wantID, tt.wantRole, tt.wantAdmin)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func personalToken(t *testing.T) (string, Subject) {
|
||||||
|
t.Helper()
|
||||||
|
raw, subject, err := NewPersonalToken()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return raw, subject
|
||||||
|
}
|
||||||
@@ -255,12 +255,13 @@ type Module struct {
|
|||||||
store *store.Store
|
store *store.Store
|
||||||
log *slog.Logger
|
log *slog.Logger
|
||||||
credentials Credentials
|
credentials Credentials
|
||||||
|
oidc *oidcLogin
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewModule returns the governance module for orgID. The ai-sdk provider
|
// NewModule returns the governance module for orgID. The ai-sdk provider
|
||||||
// classes must already be registered.
|
// classes must already be registered.
|
||||||
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string) *Module {
|
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string) *Module {
|
||||||
return &Module{orgID: orgID, store: store.New(db), log: log}
|
return &Module{orgID: orgID, store: store.New(db), log: log, oidc: &oidcLogin{}}
|
||||||
}
|
}
|
||||||
|
|
||||||
// UseCredentials gives the module the sealed store a model's key reference
|
// UseCredentials gives the module the sealed store a model's key reference
|
||||||
|
|||||||
@@ -356,7 +356,11 @@ type PersonalTokenStore interface {
|
|||||||
|
|
||||||
// UsePersonalToken admits a presented token, refusing expired tokens and
|
// UsePersonalToken admits a presented token, refusing expired tokens and
|
||||||
// recording last use at most once per minute.
|
// recording last use at most once per minute.
|
||||||
func UsePersonalToken(ctx context.Context, store PersonalTokenStore, subject Subject, now time.Time) error {
|
func UsePersonalToken(ctx context.Context, store interface {
|
||||||
|
PersonalTokenOf(context.Context, Subject) (PersonalToken, error)
|
||||||
|
TouchPersonalToken(context.Context, Subject, time.Time) error
|
||||||
|
}, subject Subject, now time.Time,
|
||||||
|
) error {
|
||||||
token, err := store.PersonalTokenOf(ctx, subject)
|
token, err := store.PersonalTokenOf(ctx, subject)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -0,0 +1,198 @@
|
|||||||
|
package governance
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
gooidc "github.com/coreos/go-oidc/v3/oidc"
|
||||||
|
"golang.org/x/oauth2"
|
||||||
|
)
|
||||||
|
|
||||||
|
// oidcCallbackPath must match the redirect URI registered at the provider:
|
||||||
|
// the provider returns the browser to the path it was given.
|
||||||
|
const oidcCallbackPath = "/oauth2/callback"
|
||||||
|
|
||||||
|
// oidcLogin runs the browser sign-in against the provider the authentication
|
||||||
|
// settings name. It keeps the provider's discovery and signing-key cache
|
||||||
|
// until the settings change, so a change applies without a restart.
|
||||||
|
type oidcLogin struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
current AuthenticationSettings
|
||||||
|
provider *oidcProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
// flow returns the authorization code flow for the saved settings, or
|
||||||
|
// ErrNoCredential when no provider is configured.
|
||||||
|
func (o *oidcLogin) flow(ctx context.Context, settings AuthenticationSettingsStore) (*oidcFlow, error) {
|
||||||
|
value, err := settings.AuthenticationSettings(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if value.PublicURL == "" || value.OIDCIssuer == "" {
|
||||||
|
return nil, ErrNoCredential
|
||||||
|
}
|
||||||
|
o.mu.Lock()
|
||||||
|
defer o.mu.Unlock()
|
||||||
|
if o.provider == nil || o.current != value {
|
||||||
|
provider, err := newOIDCProvider(value.OIDCIssuer, value.OIDCAudience)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
o.provider, o.current = provider, value
|
||||||
|
}
|
||||||
|
return newOIDCFlow(o.provider, value.OIDCClientID, value.PublicURL+oidcCallbackPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
// oidcProvider discovers the identity provider on first use and keeps the
|
||||||
|
// result. A provider that is down does not stop the binary: discovery is
|
||||||
|
// retried on the next sign-in.
|
||||||
|
type oidcProvider struct {
|
||||||
|
issuer string
|
||||||
|
audience string
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
discovered *gooidc.Provider
|
||||||
|
}
|
||||||
|
|
||||||
|
func newOIDCProvider(issuer, audience string) (*oidcProvider, error) {
|
||||||
|
issuer, audience = strings.TrimSpace(issuer), strings.TrimSpace(audience)
|
||||||
|
if issuer == "" {
|
||||||
|
return nil, fmt.Errorf("oidc: issuer is required")
|
||||||
|
}
|
||||||
|
// Without an audience a token the provider minted for a different
|
||||||
|
// service would authenticate here.
|
||||||
|
if audience == "" {
|
||||||
|
return nil, fmt.Errorf("oidc: audience is required")
|
||||||
|
}
|
||||||
|
return &oidcProvider{issuer: issuer, audience: audience}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *oidcProvider) get(ctx context.Context) (*gooidc.Provider, error) {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
if p.discovered != nil {
|
||||||
|
return p.discovered, nil
|
||||||
|
}
|
||||||
|
discovered, err := gooidc.NewProvider(ctx, p.issuer)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%w: discover %q: %w", ErrProviderUnavailable, p.issuer, err)
|
||||||
|
}
|
||||||
|
p.discovered = discovered
|
||||||
|
return discovered, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// oidcFlow runs the authorization code flow with PKCE. Discovery, the code
|
||||||
|
// exchange, PKCE and token verification are the libraries'.
|
||||||
|
type oidcFlow struct {
|
||||||
|
provider *oidcProvider
|
||||||
|
clientID string
|
||||||
|
redirectURL string
|
||||||
|
}
|
||||||
|
|
||||||
|
func newOIDCFlow(provider *oidcProvider, clientID, redirectURL string) (*oidcFlow, error) {
|
||||||
|
if strings.TrimSpace(clientID) == "" {
|
||||||
|
return nil, fmt.Errorf("oidc: client id is required for the browser flow")
|
||||||
|
}
|
||||||
|
return &oidcFlow{provider: provider, clientID: clientID, redirectURL: redirectURL}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *oidcFlow) oauth(ctx context.Context) (oauth2.Config, error) {
|
||||||
|
discovered, err := f.provider.get(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return oauth2.Config{}, err
|
||||||
|
}
|
||||||
|
return oauth2.Config{
|
||||||
|
ClientID: f.clientID,
|
||||||
|
Endpoint: discovered.Endpoint(),
|
||||||
|
RedirectURL: f.redirectURL,
|
||||||
|
// openid makes the provider return a subject at all; profile and
|
||||||
|
// email make a name available for display.
|
||||||
|
Scopes: []string{gooidc.ScopeOpenID, "profile", "email"},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AuthCodeURL returns the provider URL to send a browser to, with the
|
||||||
|
// audience requested, and the PKCE verifier.
|
||||||
|
func (f *oidcFlow) AuthCodeURL(ctx context.Context, state string) (string, string, error) {
|
||||||
|
config, err := f.oauth(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return "", "", err
|
||||||
|
}
|
||||||
|
codeVerifier := oauth2.GenerateVerifier()
|
||||||
|
url := config.AuthCodeURL(state,
|
||||||
|
oauth2.S256ChallengeOption(codeVerifier),
|
||||||
|
oauth2.SetAuthURLParam("nonce", oauth2.S256ChallengeFromVerifier(codeVerifier)),
|
||||||
|
oauth2.SetAuthURLParam("audience", f.provider.audience),
|
||||||
|
)
|
||||||
|
return url, codeVerifier, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exchange trades the code for the provider's tokens, verifies the ID token
|
||||||
|
// against the browser client and binds its nonce to the PKCE verifier. An
|
||||||
|
// access token is not proof of a browser sign-in.
|
||||||
|
func (f *oidcFlow) Exchange(ctx context.Context, code, codeVerifier string) (ProviderSession, error) {
|
||||||
|
config, err := f.oauth(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return ProviderSession{}, err
|
||||||
|
}
|
||||||
|
token, err := config.Exchange(ctx, strings.TrimSpace(code), oauth2.VerifierOption(codeVerifier))
|
||||||
|
if err != nil {
|
||||||
|
return ProviderSession{}, fmt.Errorf("%w: exchange code: %w", ErrCredentialRejected, err)
|
||||||
|
}
|
||||||
|
rawIDToken, ok := token.Extra("id_token").(string)
|
||||||
|
if !ok || rawIDToken == "" {
|
||||||
|
return ProviderSession{}, fmt.Errorf("%w: provider returned no ID token", ErrCredentialRejected)
|
||||||
|
}
|
||||||
|
discovered, err := f.provider.get(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return ProviderSession{}, err
|
||||||
|
}
|
||||||
|
verified, err := discovered.Verifier(&gooidc.Config{ClientID: f.clientID}).Verify(ctx, rawIDToken)
|
||||||
|
if err != nil {
|
||||||
|
return ProviderSession{}, fmt.Errorf("%w: verify ID token: %w", ErrCredentialRejected, err)
|
||||||
|
}
|
||||||
|
if verified.Nonce != oauth2.S256ChallengeFromVerifier(codeVerifier) {
|
||||||
|
return ProviderSession{}, fmt.Errorf("%w: ID token nonce mismatch", ErrCredentialRejected)
|
||||||
|
}
|
||||||
|
credential, err := credentialOf(verified)
|
||||||
|
if err != nil {
|
||||||
|
return ProviderSession{}, err
|
||||||
|
}
|
||||||
|
expires := token.Expiry
|
||||||
|
if credential.Expires.Before(expires) || expires.IsZero() {
|
||||||
|
expires = credential.Expires
|
||||||
|
}
|
||||||
|
return ProviderSession{Credential: credential, Token: rawIDToken, Expires: expires}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// credentialOf reads what a verified token proved. Claims are read only after
|
||||||
|
// verification: an unverified token selects nothing.
|
||||||
|
func credentialOf(token *gooidc.IDToken) (Credential, error) {
|
||||||
|
var claims struct {
|
||||||
|
Subject string `json:"sub"`
|
||||||
|
ClientID string `json:"client_id"`
|
||||||
|
Scope string `json:"scope"`
|
||||||
|
Scopes []string `json:"scp"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Verified bool `json:"email_verified"`
|
||||||
|
}
|
||||||
|
_ = token.Claims(&claims)
|
||||||
|
subject := Subject{Issuer: token.Issuer, Subject: strings.TrimSpace(claims.Subject)}
|
||||||
|
if subject.Subject == "" {
|
||||||
|
subject.Subject = strings.TrimSpace(claims.ClientID)
|
||||||
|
}
|
||||||
|
if subject.Subject == "" {
|
||||||
|
return Credential{}, fmt.Errorf("%w: token asserts neither sub nor client_id", ErrCredentialRejected)
|
||||||
|
}
|
||||||
|
email := ""
|
||||||
|
if claims.Verified {
|
||||||
|
email = strings.TrimSpace(claims.Email)
|
||||||
|
}
|
||||||
|
scopes := claims.Scopes
|
||||||
|
if len(scopes) == 0 {
|
||||||
|
scopes = strings.Fields(claims.Scope)
|
||||||
|
}
|
||||||
|
return Credential{Subject: subject, Email: email, Scopes: scopes, Expires: token.Expiry}, nil
|
||||||
|
}
|
||||||
+13
-1
@@ -50,7 +50,19 @@ function qs(params?: QueryParams): string {
|
|||||||
// away the only part an operator can act on. Only a text/plain body is read:
|
// away the only part an operator can act on. Only a text/plain body is read:
|
||||||
// a proxy's HTML error page must not pass through as the reason.
|
// a proxy's HTML error page must not pass through as the reason.
|
||||||
async function errorMessage(res: Response): Promise<string> {
|
async function errorMessage(res: Response): Promise<string> {
|
||||||
if ((res.headers.get("Content-Type") ?? "").includes("text/plain")) {
|
const type = res.headers.get("Content-Type") ?? "";
|
||||||
|
// The single binary answers with an RFC 9457 problem whose detail is the
|
||||||
|
// reason.
|
||||||
|
if (type.includes("application/problem+json")) {
|
||||||
|
try {
|
||||||
|
const detail = ((await res.json()) as { detail?: unknown }).detail;
|
||||||
|
if (typeof detail === "string" && detail) return detail.slice(0, 200);
|
||||||
|
} catch {
|
||||||
|
// Unreadable problem; fall through to the status.
|
||||||
|
}
|
||||||
|
return `${res.status} ${res.statusText}`;
|
||||||
|
}
|
||||||
|
if (type.includes("text/plain")) {
|
||||||
try {
|
try {
|
||||||
const body = (await res.text()).trim();
|
const body = (await res.text()).trim();
|
||||||
if (body) return body.split("\n")[0].slice(0, 200);
|
if (body) return body.split("\n")[0].slice(0, 200);
|
||||||
|
|||||||
+2
-2
@@ -15,8 +15,8 @@ export default defineConfig({
|
|||||||
outDir: "dist",
|
outDir: "dist",
|
||||||
emptyOutDir: true,
|
emptyOutDir: true,
|
||||||
rollupOptions: {
|
rollupOptions: {
|
||||||
// index.html is the old services' dashboard; archie.html is the single
|
// index.html is the dashboard the old services and the single binary
|
||||||
// binary's, which calls only the new API.
|
// both serve; the binary still serves archie.html at /archie.html.
|
||||||
input: { main: "index.html", archie: "archie.html" },
|
input: { main: "index.html", archie: "archie.html" },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
Reference in new issue
Block a user