Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions .github/workflows/coweft-identity.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
name: CoWeft identity boundary
on:
push:
branches: ['feat/coweft-oidc']
pull_request:
paths: ['apps/api-go/oidcprovider/**','apps/api-go/service/oidc_provider.go','apps/api-go/router/oidc_provider.go','apps/api-go/router/oauth_server.go','.github/workflows/coweft-identity.yml']
permissions:
contents: read
jobs:
provider:
runs-on: ubuntu-latest
defaults:
run:
working-directory: apps/api-go
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version-file: apps/api-go/go.mod
cache-dependency-path: apps/api-go/go.sum
- run: go test -race ./oidcprovider
- run: go test ./service ./router -run 'OIDC|OAuth' -count=1
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,6 @@
[submodule "packages/codewhale-lmm-provider"]
path = packages/codewhale-lmm-provider
url = https://github.com/TokenNotIncluded/codewhale-lmm-provider.git
[submodule "apps/coweft"]
path = apps/coweft
url = https://github.com/TokenNotIncluded/coweft.git
96 changes: 96 additions & 0 deletions apps/api-go/oidcprovider/attestation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package oidcprovider

import (
"context"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"io"
"net/http"
"time"
)

// AttestationHandler requires BOTH the registered resource's Basic credential
// and an active user grant in the JSON body. A user token alone cannot fabricate
// an origin-node publication. The result is public evidence, NOT a bearer token.
func (p *Provider) AttestationHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Content-Type-Options", "nosniff")
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if !p.transport(r) {
fail(w, 400, "https_required")
return
}
if !p.allowed(r) {
fail(w, 429, "rate_limited")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
r = r.WithContext(ctx)
id, secret, ok := r.BasicAuth()
resource, found := p.resources[id]
if len(r.Header.Values("Authorization")) != 1 || !ok || !found || !same(secret, resource.Secret) {
fail(w, 401, "invalid_resource_client")
return
}
if r.Header.Get("Content-Type") != "application/json" {
fail(w, 400, "invalid_request")
return
}
var request struct {
Token string `json:"token"`
Digest string `json:"digest"`
Purpose string `json:"purpose"`
}
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 2048))
decoder.DisallowUnknownFields()
if decoder.Decode(&request) != nil || decoder.Decode(new(any)) != io.EOF || request.Purpose != "public-thread-v1" {
fail(w, 400, "invalid_request")
return
}
g, _, err := p.access(ctx, request.Token)
if err != nil {
fail(w, 401, "invalid_token")
return
}
if g.Request.Resource != resource.URI || !contains(g.Request.Scopes, "coweft:write") {
fail(w, 403, "insufficient_scope")
return
}
digestBytes, err := base64.RawURLEncoding.DecodeString(request.Digest)
if err != nil || len(digestBytes) != 32 || base64.RawURLEncoding.EncodeToString(digestBytes) != request.Digest {
fail(w, 400, "invalid_digest")
return
}
claims := map[string]any{
"iss": p.config.Issuer, "aud": "urn:coweft:public-thread-v1", "sub": g.Identity.Subject,
"resource": g.Request.Resource, "client_id": g.Request.ClientID, "controller": g.Controller,
"digest": request.Digest, "purpose": request.Purpose, "iat": time.Now().Unix(),
}
if contains(g.Request.Scopes, "profile") {
claims["name"] = g.Identity.Name
}
header, _ := json.Marshal(map[string]string{"alg": "RS256", "typ": "coweft-event+jwt", "kid": p.kid})
body, err := json.Marshal(claims)
if err != nil {
fail(w, 503, "server_error")
return
}
unsigned := base64.RawURLEncoding.EncodeToString(header) + "." + base64.RawURLEncoding.EncodeToString(body)
sum := sha256.Sum256([]byte(unsigned))
signature, err := rsa.SignPKCS1v15(rand.Reader, p.config.Key, crypto.SHA256, sum[:])
if err != nil {
fail(w, 503, "server_error")
return
}
jsonResponse(w, 200, map[string]string{"receipt": unsigned + "." + base64.RawURLEncoding.EncodeToString(signature), "purpose": "public-thread-v1"})
})
}
73 changes: 73 additions & 0 deletions apps/api-go/oidcprovider/attestation_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package oidcprovider

import (
"context"
"crypto"
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
)

func receiptRequest(token, contentDigest string) *http.Request {
body, _ := json.Marshal(map[string]string{"token": token, "digest": contentDigest, "purpose": "public-thread-v1"})
request := httptest.NewRequest("POST", "https://api.lmm.best/api/oidc/attest", strings.NewReader(string(body)))
request.Header.Set("Content-Type", "application/json")
request.SetBasicAuth("coweft", strings.Repeat("s", 32))
return request
}
func TestPublicReceiptRequiresNodeAndUserAndCannotBecomeACredential(t *testing.T) {
p, _ := setup(t)
tokens := tokenFor(t, p)
access := tokens["access_token"].(string)
request := receiptRequest(access, digest("public content"))
response := httptest.NewRecorder()
p.AttestationHandler().ServeHTTP(response, request)
if response.Code != 200 {
t.Fatal(response.Code, response.Body.String())
}
var result map[string]string
json.Unmarshal(response.Body.Bytes(), &result)
parts := strings.Split(result["receipt"], ".")
if len(parts) != 3 {
t.Fatal("invalid receipt")
}
headerBytes, _ := base64.RawURLEncoding.DecodeString(parts[0])
var header map[string]string
json.Unmarshal(headerBytes, &header)
if header["typ"] != "coweft-event+jwt" {
t.Fatal("wrong receipt type")
}
signature, _ := base64.RawURLEncoding.DecodeString(parts[2])
sum := sha256.Sum256([]byte(parts[0] + "." + parts[1]))
if rsa.VerifyPKCS1v15(&p.config.Key.PublicKey, crypto.SHA256, sum[:], signature) != nil {
t.Fatal("signature invalid")
}
claimBytes, _ := base64.RawURLEncoding.DecodeString(parts[1])
var claims map[string]any
json.Unmarshal(claimBytes, &claims)
if claims["digest"] != digest("public content") || claims["sub"] != "lmm:7" || claims["aud"] != "urn:coweft:public-thread-v1" {
t.Fatal(claims)
}
if _, _, err := p.access(context.Background(), result["receipt"]); err == nil {
t.Fatal("public receipt accepted as bearer token")
}
request = receiptRequest(access, digest("forged origin"))
request.Header.Set("Authorization", "Bearer "+access)
response = httptest.NewRecorder()
p.AttestationHandler().ServeHTTP(response, request)
if response.Code != 401 {
t.Fatal("user token alone could impersonate resource approval")
}
post(p, "/api/oidc/revoke", url.Values{"token": {access}, "client_id": {"coweft-web"}}, false)
response = httptest.NewRecorder()
p.AttestationHandler().ServeHTTP(response, receiptRequest(access, digest("public content")))
if response.Code != 401 {
t.Fatal("revoked grant could issue receipt")
}
}
Loading
Loading