/

Ambitwin · source-available, not open source · © 2026 Nicolò Ghignatti

Auth Contracts

Keywords on this page
WordMeaningExample
Go moduleA Go library other Go code importsbackend/libs/auth-contracts
ClaimsWhat the token says about the callersub, accountName, memberships
MembershipOne domain the caller belongs to, with one role there{domain: "unibo", role: "standard_customer"}
Role weightA number that ranks roles: higher means more powerbusiness_admin = 80
Role ladderAll roles with their weightsroles.json
HMACA signature made with a secret both sides holdX-Signature: bd3ae5…
Golden vectorA fixed input with its known right answer, checked by every languagesecret + body → signature
MiddlewareCode that runs before a route handler and can stop the requestRequireSignature

Go module at backend/libs/auth-contracts. It holds three things every Go service must agree on:

FileHoldsWhy shared
claims.goStandardClaims, MembershipThe shape of the caller, same in every service
roles.go + roles.jsonRoleWeights, Can()One ranking of roles, read by every language
internalsig.goSign, Verify, RequireSignatureOne way for a service to prove “this call is from another Ambitwin service”

Standard library only: no outside dependency. registry and provisioner need the signature code but never check a token, so this module must not pull in JWT libraries.


Who uses what

ItemUsed byFor
StandardClaimsclaims-gateway signer.Sign, auth-middlewareBuild the token; read it back
Membershipclaims-gateway tenancyclient, tenancy MembershipsFor, auth-policyCarry memberships between services
RoleWeightsclaims-gateway exchange.go, tenancy service and handler, auth-policy accountEntityPick the strongest role; compare roles
Can()tenancy service/tenancy.go“Is this role at least business_admin?”
roles.json, read as a filedigital-twin service/authz.rs, telemetry kernel/authz.rs, notification domain/identity.rs (include_str!); agent app/roles.py (at start-up)Same ladder outside Go
Signprovisioner (both clients), claims-gateway tenancyclientSign an internal call
RequireSignatureregistry and tenancy /internal/* routesCheck an internal call

RoleIn, CanIn and Tenants on StandardClaims have no caller outside this module’s tests. tenancy has its own roleIn in internal/api/handler.go, which keeps the highest role when one domain appears twice.


1. StandardClaims

Shape

{"sub":"8f1c2e3a-4b5d-4e6f-9a1b-2c3d4e5f6a7b","accountName":"mario",
 "sid":"b2a9c1d0-1234-4e6f-9a1b-2c3d4e5f6a7b",
 "memberships":[{"domain":"unibo","role":"standard_customer","externalId":"eppn:mario@unibo.it"}]}
JSONGo fieldMeaning
subSubAccount id. Every access decision keys on it
accountNameAccountNameName shown to people
sidSIDSession id. signer.Sign makes a new UUID when empty
membershipsMembershipsList of {domain, role, externalId}
externalIdMembership.ExternalIDThe identity provider’s id for this membership. Left out of JSON when empty

The type has no field for a tier or an identity provider. A direct sign-up and a federated one reach every service in this same shape.

Helper methods

MethodGivesExample, with acme: business_admin, unibo: standard_customer
RoleIn(domain)Role in that domain, and whether one exists. First match winsRoleIn("acme") = business_admin, true
CanIn(domain, required)RoleIn, then CanCanIn("unibo", "business_admin") = false
Tenants()Every domain, in membership order["acme", "unibo"]

2. The role ladder

Data

roles.json, embedded in the binary with //go:embed:

RoleWeight
admin100
business_admin80
business_staff60
standard_customer10

How Can(have, need) decides

flowchart TD
    S["Can(principalRole, requiredRole)"] --> A{"principalRole in RoleWeights?"}
    A -- no --> D1["false"]
    A -- yes --> B{"requiredRole in RoleWeights?"}
    B -- no --> D2["false"]
    B -- yes --> C{"weight(have) >= weight(need)?"}
    C -- yes --> T["true"]
    C -- no --> D3["false"]
CallWeightsResultWhy
Can("admin", "business_admin")100 ≥ 80trueHigher passes
Can("business_admin", "business_admin")80 ≥ 80trueEqual passes
Can("standard_customer", "business_admin")10 ≥ 80falseLower fails
Can("not-a-role", "standard_customer")unknownfalseUnknown caller role denies
Can("business_admin", "not-a-role")unknownfalseA typo in the required role denies. Reading it as weight 0 would let everyone through

Where the ladder is read

flowchart LR
    J["roles.json"] -- "go:embed" --> G["Go: RoleWeights"]
    J -- "include_str! at build" --> R1["digital-twin"]
    J -- "include_str! at build" --> R2["telemetry"]
    J -- "include_str! at build" --> R3["notification"]
    J -- "read at start-up" --> P["agent app/roles.py"]

One file, five readers, no copy. Changing a weight changes every language at the next build or start.


3. Internal signatures

Some calls carry no person: provisioner setting up a new organization acts for nobody, so there is no claims header to forward. These calls prove who sent them with an HMAC over the body.

The rule

Who signs, who checks

CallerFunctionRoute on the receiverBody
provisioner registryclientSign(secret, nil)GET /internal/organizations/pending on registryempty
provisioner registryclientSign(secret, raw)POST /internal/organizations/{id}/status on registryJSON
provisioner tenancyclientSign(secret, body)POST /internal/domains on tenancyJSON
claims-gateway tenancyclientSign(secret, nil)GET /internal/memberships?accountId=… on tenancyempty
claims-gateway tenancyclientSign(secret, body)POST /internal/provision on tenancyJSON

registry also has POST /internal/organizations/{id}/suspend behind the same check.

A signed call end to end

sequenceDiagram
    autonumber
    participant P as provisioner<br/>tenancyclient
    participant AC as auth-contracts
    participant M as tenancy<br/>RequireSignature
    participant H as tenancy<br/>internalCreateDomain
    P->>P: json.Marshal(domain request) gives body
    P->>AC: Sign(secret, body)
    AC-->>P: hex HMAC-SHA256
    P->>M: POST /internal/domains, X-Signature, body
    M->>M: header empty? 403 "missing signature"
    M->>M: io.ReadAll(r.Body). fails? 400 "cannot read body"
    M->>M: put body back: r.Body = NopCloser(bytes)
    M->>AC: Verify(secret, body, signature)
    AC->>AC: Sign(secret, body) again, hmac.Equal
    alt match
        AC-->>M: true
        M->>H: next.ServeHTTP
        H->>H: reads the same body again
    else no match
        AC-->>M: false
        M-->>P: 403 "invalid signature"
    end

Data at each step

Example from the shared fixture schemas/fixtures/internal-signature.json: secret an-internal-secret-that-is-at-least-32-bytes.

StepData
1Body {"buildingId":"bldg-1","status":"ready"} (40 bytes)
3Signature bd3ae57b5d5672d04b5c376ddd2b2fe60a348a9c5d151d631d6fd38241772418
4Header X-Signature: bd3ae57b…2418, same 40 bytes as body
6Those 40 bytes in memory
7A new reader over the same 40 bytes, so the handler can read them
9Recomputed signature, equal to step 3
11Handler sees the original body

A body with one extra space gives a different signature, so step 9 fails with 403.

Why each check gives its status

CaseStatusWhy
No X-Signature403Not a known service
Body cannot be read400The connection broke. Saying 403 would tell the caller its secret is wrong when it is not
Wrong signature403Wrong secret, or the body changed on the way

Same rule outside Go

telemetry checks device batches with its own Rust code (adapters/ingest_auth.rs) and its own key. Both sides check the same golden vectors in schemas/fixtures/internal-signature.json:

CaseBodySignature starts
empty body(nothing)52a0b3ef
json body{"buildingId":"bldg-1","status":"ready"}bd3ae57b
unicode{"name":"Aula Magna — Cesena"}2ec44f60

Change the algorithm on one side and the other side’s test fails.


Tests

TestChecks
roles_test.goHigher and equal pass; lower denied; unknown caller role denied; unknown required role denied; weights are 100, 80, 60, 10
claims_test.goRoleIn finds the role and misses a foreign domain; CanIn is scoped to one domain; Tenants order
conformance_test.goschemas/fixtures/standard-claims.json parses into StandardClaims, has sub, accountName, sid, at least one membership, and every role is on the ladder
internalsig_test.goEvery golden vector signs and verifies; a one-byte change, another secret, an empty signature all fail; the handler still reads the body; missing or wrong signature is 403; an unreadable body is 400 and the handler never runs

The same claims fixture is checked by Rust (schemas/claims-schema/tests/conformance.rs) and Python (agent/tests/unit/test_claims_conformance.py).

mise exec -- go test ./...   # in backend/libs/auth-contracts

Gaps