Add account device API and APK build versioning

This commit is contained in:
2026-11-17 21:15:39 +02:00
parent 9a10f639cc
commit a11ccf15c5
11 changed files with 901 additions and 17 deletions
+5 -2
View File
@@ -2,7 +2,7 @@
Self-hosted, username-based Android-to-Android encrypted voice calling project. Self-hosted, username-based Android-to-Android encrypted voice calling project.
**Status:** development scaffold. M1 local Go/Docker infrastructure has been verified; M0 feasibility and the M3 Android foundation remain in progress. This is not a working secure calling product. The cryptographic handshake, SFrame media transforms, WebRTC integration, push delivery and production hardening are not implemented. **Status:** development scaffold. M1 local Go/Docker infrastructure is verified, and the M2 account/device API flow passes a local smoke check. M0 feasibility and M3 Android verification remain open. This is not a working secure calling product. The cryptographic handshake, SFrame media transforms, WebRTC integration, push delivery and production hardening are not implemented.
## Architecture baseline ## Architecture baseline
- Android: Kotlin, Jetpack Compose, Android Keystore, Core-Telecom - Android: Kotlin, Jetpack Compose, Android Keystore, Core-Telecom
@@ -20,7 +20,7 @@ Self-hosted, username-based Android-to-Android encrypted voice calling project.
3. Check API health: `curl http://localhost:8080/healthz` 3. Check API health: `curl http://localhost:8080/healthz`
4. Check signaling health: `curl http://localhost:8081/healthz` 4. Check signaling health: `curl http://localhost:8081/healthz`
The API currently provides only health and a placeholder registration endpoint. Signaling currently accepts WebSocket connections but does not yet implement authenticated call routing. Do not expose this scaffold to the public Internet. The API has development account/session endpoints and a provisional P-256 public device directory. Signaling does not yet implement authenticated call routing. Do not expose this scaffold to the public Internet.
## Repository layout ## Repository layout
- `backend/`: Go services - `backend/`: Go services
@@ -42,8 +42,11 @@ Android build (requires Android Studio / Android SDK and a locally installed Gra
```bash ```bash
cd android cd android
gradle assembleDebug gradle assembleDebug
gradle archiveDebugApk
``` ```
`archiveDebugApk` writes a build-identified copy to `android/app/build/outputs/versioned-apk/`. See [Android build versioning](docs/ANDROID-BUILDS.md) for CI and release overrides.
## Security rules ## Security rules
1. Never send private keys, shared secrets or plaintext audio to the backend. 1. Never send private keys, shared secrets or plaintext audio to the backend.
2. Do not mark a call secure until peer identity and media encryption are authenticated. 2. Do not mark a call secure until peer identity and media encryption are authenticated.
+59 -2
View File
@@ -1,9 +1,57 @@
import org.gradle.api.tasks.Copy
import java.time.Instant
plugins { plugins {
id("com.android.application") id("com.android.application")
id("org.jetbrains.kotlin.android") id("org.jetbrains.kotlin.android")
id("org.jetbrains.kotlin.plugin.compose") id("org.jetbrains.kotlin.plugin.compose")
} }
fun buildSetting(propertyName: String, environmentName: String) =
providers.gradleProperty(propertyName).orElse(providers.environmentVariable(environmentName))
val buildInstant = Instant.now()
val gitRevision = runCatching {
val process = ProcessBuilder("git", "rev-parse", "--short=12", "HEAD")
.directory(rootProject.projectDir.parentFile)
.redirectErrorStream(true)
.start()
val output = process.inputStream.bufferedReader().use { it.readText().trim() }
if (process.waitFor() == 0 && output.matches(Regex("[0-9a-fA-F]{7,40}"))) output else null
}.getOrNull()
val isGitDirty = runCatching {
val process = ProcessBuilder("git", "status", "--porcelain")
.directory(rootProject.projectDir.parentFile)
.redirectErrorStream(true)
.start()
val output = process.inputStream.bufferedReader().use { it.readText() }
process.waitFor() == 0 && output.isNotBlank()
}.getOrDefault(false)
val defaultBuildId = "${gitRevision ?: "local"}${if (isGitDirty) "-dirty" else ""}-${buildInstant.toEpochMilli()}"
val appVersion = buildSetting("appVersion", "APP_VERSION").orElse("0.1.0").get()
val appBuildId = buildSetting("appBuildId", "APP_BUILD_ID")
.orElse(defaultBuildId)
.get()
val appVersionCode = buildSetting("appVersionCode", "APP_VERSION_CODE")
.orElse(buildInstant.epochSecond.toString())
.get()
.toIntOrNull()
?: error("appVersionCode/APP_VERSION_CODE must be a positive 32-bit integer")
require(appVersionCode in 1..2_100_000_000) {
"appVersionCode/APP_VERSION_CODE must be between 1 and 2,100,000,000"
}
require(appVersion.isNotBlank() && appBuildId.isNotBlank()) {
"appVersion/APP_VERSION and appBuildId/APP_BUILD_ID must not be blank"
}
require(appVersion.matches(Regex("[0-9]+\\.[0-9]+\\.[0-9]+(?:-[A-Za-z0-9.-]+)?"))) {
"appVersion/APP_VERSION must be a semantic version such as 0.1.0 or 0.1.0-rc.1"
}
require(appBuildId.matches(Regex("[A-Za-z0-9._-]+"))) {
"appBuildId/APP_BUILD_ID may contain only letters, numbers, dot, underscore, and hyphen"
}
val safeBuildLabel = "${appVersion}-$appBuildId-$appVersionCode"
.replace(Regex("[^A-Za-z0-9._-]"), "_")
android { android {
namespace = "com.ee2e.app" namespace = "com.ee2e.app"
compileSdk = 35 compileSdk = 35
@@ -11,8 +59,8 @@ android {
applicationId = "com.ee2e.app" applicationId = "com.ee2e.app"
minSdk = 29 minSdk = 29
targetSdk = 35 targetSdk = 35
versionCode = 1 versionCode = appVersionCode
versionName = "0.1.0" versionName = "$appVersion+$appBuildId"
} }
compileOptions { compileOptions {
sourceCompatibility = JavaVersion.VERSION_21 sourceCompatibility = JavaVersion.VERSION_21
@@ -26,6 +74,15 @@ android {
buildFeatures { compose = true } buildFeatures { compose = true }
} }
tasks.register<Copy>("archiveDebugApk") {
group = "build"
description = "Copies the debug APK to a versioned filename for build tracking."
dependsOn("assembleDebug")
from(layout.buildDirectory.file("outputs/apk/debug/app-debug.apk"))
into(layout.buildDirectory.dir("outputs/versioned-apk"))
rename { "ee2e-phone-calls-$safeBuildLabel-debug.apk" }
}
dependencies { dependencies {
implementation(platform("androidx.compose:compose-bom:2024.12.01")) implementation(platform("androidx.compose:compose-bom:2024.12.01"))
implementation("androidx.activity:activity-compose:1.10.0") implementation("androidx.activity:activity-compose:1.10.0")
+1 -1
View File
@@ -1,4 +1,4 @@
FROM golang:1.23-alpine AS build FROM golang:1.26-alpine AS build
WORKDIR /src WORKDIR /src
COPY go.mod go.sum* ./ COPY go.mod go.sum* ./
RUN go mod download RUN go mod download
+14 -1
View File
@@ -1 +1,14 @@
Run `go mod tidy`, then `go test ./...`. Services are deliberately incomplete placeholders. ## API scaffold
The API service currently provides:
- `POST /api/v1/auth/register` and `POST /api/v1/auth/login` for username/password accounts. Passwords are stored as Argon2id hashes; successful calls return an opaque 30-day bearer token whose SHA-256 digest is stored in PostgreSQL.
- `POST /api/v1/auth/logout` to revoke the current session.
- `POST /api/v1/devices/challenges`, followed by `POST /api/v1/devices`, to register an active device after proof of possession of an ECDSA P-256 signing key.
- `GET /api/v1/directory/{username}/devices` to return active public device keys, and `DELETE /api/v1/devices/{deviceID}` for the owning account to revoke a device.
Device registration currently accepts only the Android foundation's `ecdsa-p256-sha256-v1` public key. The client signs `ee2e-device-registration-v1\0 || challenge_id || \0 || challenge_bytes` with ECDSA/SHA-256; challenge IDs expire after five minutes and are one use. The key format is classical and provisional; it does not implement PQXDH, signed prekey bundles, or the final directory protocol. No private keys are accepted or stored. API registration does not establish a verified peer identity or make calls secure. Rate limiting, account recovery, TLS deployment, and operational security remain incomplete.
The API applies its additive database migration at startup. PostgreSQL must first have the base tables from `infrastructure/postgres/init.sql`. Use the `DATABASE_URL` environment variable; do not log or commit connection strings or bearer tokens.
Run `go test ./...` to execute the backend tests. Service and account functionality remains a development scaffold.
@@ -0,0 +1,24 @@
CREATE TABLE IF NOT EXISTS sessions (
token_hash BYTEA PRIMARY KEY CHECK (octet_length(token_hash) = 32),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
expires_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX IF NOT EXISTS sessions_user_id_idx ON sessions(user_id);
CREATE INDEX IF NOT EXISTS sessions_expires_at_idx ON sessions(expires_at);
CREATE TABLE IF NOT EXISTS device_registration_challenges (
id UUID PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
nonce BYTEA NOT NULL CHECK (octet_length(nonce) = 32),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
expires_at TIMESTAMPTZ NOT NULL,
consumed_at TIMESTAMPTZ
);
CREATE INDEX IF NOT EXISTS device_registration_challenges_user_id_idx
ON device_registration_challenges(user_id);
CREATE UNIQUE INDEX IF NOT EXISTS devices_active_identity_key_idx
ON devices(user_id, identity_public_key) WHERE status = 'active';
+497
View File
@@ -0,0 +1,497 @@
package main
import (
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"database/sql"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"regexp"
"strings"
"time"
)
const maxJSONBodyBytes = 8 * 1024
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
var uuidPattern = regexp.MustCompile(`(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`)
type contextKey string
const authenticatedUserIDKey contextKey = "authenticated-user-id"
const authenticatedTokenHashKey contextKey = "authenticated-token-hash"
type credentialsRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
type deviceRegistrationRequest struct {
ChallengeID string `json:"challenge_id"`
IdentityKey string `json:"identity_public_key"`
ChallengeProof string `json:"challenge_signature"`
}
func (s *apiServer) register(w http.ResponseWriter, r *http.Request) {
var request credentialsRequest
if !decodeJSON(w, r, &request) {
return
}
if !usernamePattern.MatchString(request.Username) || len(request.Password) < 12 || len(request.Password) > 1024 {
writeError(w, http.StatusBadRequest, "username or password does not meet requirements")
return
}
passwordHash, err := s.passwords.hash(request.Password)
if errors.Is(err, errPasswordCapacity) {
writeError(w, http.StatusServiceUnavailable, "authentication is busy; retry shortly")
return
}
if err != nil {
writeError(w, http.StatusInternalServerError, "could not create account")
return
}
userID, err := newUUID()
if err != nil {
writeError(w, http.StatusInternalServerError, "could not create account")
return
}
token, tokenHash, err := newSessionToken()
if err != nil {
writeError(w, http.StatusInternalServerError, "could not create account")
return
}
expiresAt := time.Now().UTC().Add(sessionLifetime)
tx, err := s.db.BeginTx(r.Context(), nil)
if err != nil {
writeError(w, http.StatusInternalServerError, "could not create account")
return
}
defer tx.Rollback()
err = tx.QueryRowContext(r.Context(),
`INSERT INTO users(id, username, password_hash) VALUES ($1, $2, $3)
ON CONFLICT (username) DO NOTHING RETURNING id::text`,
userID, request.Username, passwordHash,
).Scan(&userID)
if errors.Is(err, sql.ErrNoRows) {
writeError(w, http.StatusConflict, "username is unavailable")
return
}
if err != nil {
writeError(w, http.StatusInternalServerError, "could not create account")
return
}
if _, err := tx.ExecContext(r.Context(),
`INSERT INTO sessions(token_hash, user_id, expires_at) VALUES ($1, $2, $3)`,
tokenHash[:], userID, expiresAt,
); err != nil {
writeError(w, http.StatusInternalServerError, "could not create account")
return
}
if err := tx.Commit(); err != nil {
writeError(w, http.StatusInternalServerError, "could not create account")
return
}
writeJSON(w, http.StatusCreated, authResponse{UserID: userID, AccessToken: token, TokenType: "Bearer", ExpiresAt: expiresAt})
}
func (s *apiServer) login(w http.ResponseWriter, r *http.Request) {
var request credentialsRequest
if !decodeJSON(w, r, &request) {
return
}
if len(request.Username) > 32 || len(request.Password) == 0 || len(request.Password) > 1024 {
writeError(w, http.StatusUnauthorized, "invalid username or password")
return
}
var userID, encodedHash string
err := s.db.QueryRowContext(r.Context(),
`SELECT id::text, password_hash FROM users WHERE username = $1`, request.Username,
).Scan(&userID, &encodedHash)
if errors.Is(err, sql.ErrNoRows) {
encodedHash = s.passwords.dummyHash
} else if err != nil {
writeError(w, http.StatusInternalServerError, "could not authenticate")
return
}
valid, err := s.passwords.verify(request.Password, encodedHash)
if errors.Is(err, errPasswordCapacity) {
writeError(w, http.StatusServiceUnavailable, "authentication is busy; retry shortly")
return
}
if err != nil {
writeError(w, http.StatusInternalServerError, "could not authenticate")
return
}
if !valid || userID == "" {
writeError(w, http.StatusUnauthorized, "invalid username or password")
return
}
token, tokenHash, err := newSessionToken()
if err != nil {
writeError(w, http.StatusInternalServerError, "could not authenticate")
return
}
expiresAt := time.Now().UTC().Add(sessionLifetime)
if _, err := s.db.ExecContext(r.Context(),
`INSERT INTO sessions(token_hash, user_id, expires_at) VALUES ($1, $2, $3)`,
tokenHash[:], userID, expiresAt,
); err != nil {
writeError(w, http.StatusInternalServerError, "could not authenticate")
return
}
writeJSON(w, http.StatusOK, authResponse{UserID: userID, AccessToken: token, TokenType: "Bearer", ExpiresAt: expiresAt})
}
func (s *apiServer) logout(w http.ResponseWriter, r *http.Request) {
tokenHash, _ := r.Context().Value(authenticatedTokenHashKey).([32]byte)
if _, err := s.db.ExecContext(r.Context(), `DELETE FROM sessions WHERE token_hash = $1`, tokenHash[:]); err != nil {
writeError(w, http.StatusInternalServerError, "could not end session")
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *apiServer) requireAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
header := r.Header.Get("Authorization")
if !strings.HasPrefix(header, "Bearer ") {
writeError(w, http.StatusUnauthorized, "authentication required")
return
}
token := strings.TrimPrefix(header, "Bearer ")
decoded, err := base64.RawURLEncoding.DecodeString(token)
if err != nil || len(decoded) != 32 {
writeError(w, http.StatusUnauthorized, "authentication required")
return
}
tokenHash := sha256.Sum256(decoded)
var userID string
err = s.db.QueryRowContext(r.Context(),
`SELECT user_id::text FROM sessions WHERE token_hash = $1 AND expires_at > now()`,
tokenHash[:],
).Scan(&userID)
if errors.Is(err, sql.ErrNoRows) {
writeError(w, http.StatusUnauthorized, "authentication required")
return
}
if err != nil {
writeError(w, http.StatusServiceUnavailable, "authentication service unavailable")
return
}
ctx := context.WithValue(r.Context(), authenticatedUserIDKey, userID)
ctx = context.WithValue(ctx, authenticatedTokenHashKey, tokenHash)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func (s *apiServer) createDeviceChallenge(w http.ResponseWriter, r *http.Request) {
userID := r.Context().Value(authenticatedUserIDKey).(string)
tx, err := s.db.BeginTx(r.Context(), nil)
if err != nil {
writeError(w, http.StatusInternalServerError, "could not create device challenge")
return
}
defer tx.Rollback()
if err := tx.QueryRowContext(r.Context(), `SELECT id FROM users WHERE id = $1 FOR UPDATE`, userID).Scan(new(string)); err != nil {
writeError(w, http.StatusInternalServerError, "could not create device challenge")
return
}
if _, err := tx.ExecContext(r.Context(),
`DELETE FROM device_registration_challenges WHERE expires_at <= now() OR consumed_at IS NOT NULL`,
); err != nil {
writeError(w, http.StatusInternalServerError, "could not create device challenge")
return
}
var pending int
if err := tx.QueryRowContext(r.Context(),
`SELECT count(*) FROM device_registration_challenges WHERE user_id = $1 AND consumed_at IS NULL AND expires_at > now()`, userID,
).Scan(&pending); err != nil {
writeError(w, http.StatusInternalServerError, "could not create device challenge")
return
}
if pending >= 5 {
writeError(w, http.StatusTooManyRequests, "too many pending device challenges")
return
}
challengeID, err := newUUID()
if err != nil {
writeError(w, http.StatusInternalServerError, "could not create device challenge")
return
}
nonce := make([]byte, 32)
if _, err := rand.Read(nonce); err != nil {
writeError(w, http.StatusInternalServerError, "could not create device challenge")
return
}
expiresAt := time.Now().UTC().Add(deviceChallengeLifetime)
if _, err := tx.ExecContext(r.Context(),
`INSERT INTO device_registration_challenges(id, user_id, nonce, expires_at) VALUES ($1, $2, $3, $4)`,
challengeID, userID, nonce, expiresAt,
); err != nil {
writeError(w, http.StatusInternalServerError, "could not create device challenge")
return
}
if err := tx.Commit(); err != nil {
writeError(w, http.StatusInternalServerError, "could not create device challenge")
return
}
writeJSON(w, http.StatusCreated, map[string]any{
"challenge_id": challengeID,
"challenge": base64.StdEncoding.EncodeToString(nonce),
"expires_at": expiresAt,
})
}
func (s *apiServer) registerDevice(w http.ResponseWriter, r *http.Request) {
var request deviceRegistrationRequest
if !decodeJSON(w, r, &request) {
return
}
if !uuidPattern.MatchString(request.ChallengeID) {
writeError(w, http.StatusBadRequest, "invalid device registration proof")
return
}
publicKeyDER, err := base64.StdEncoding.Strict().DecodeString(request.IdentityKey)
if err != nil || len(publicKeyDER) == 0 || len(publicKeyDER) > 512 {
writeError(w, http.StatusBadRequest, "invalid device registration proof")
return
}
parsedKey, err := x509.ParsePKIXPublicKey(publicKeyDER)
publicKey, ok := parsedKey.(*ecdsa.PublicKey)
if err != nil || !ok || publicKey.Curve == nil || publicKey.Curve.Params().Name != elliptic.P256().Params().Name ||
publicKey.X == nil || publicKey.Y == nil || !publicKey.Curve.IsOnCurve(publicKey.X, publicKey.Y) {
writeError(w, http.StatusBadRequest, "unsupported device identity key")
return
}
signature, err := base64.StdEncoding.Strict().DecodeString(request.ChallengeProof)
if err != nil || len(signature) < 8 || len(signature) > 80 {
writeError(w, http.StatusBadRequest, "invalid device registration proof")
return
}
userID := r.Context().Value(authenticatedUserIDKey).(string)
tx, err := s.db.BeginTx(r.Context(), nil)
if err != nil {
writeError(w, http.StatusInternalServerError, "could not register device")
return
}
defer tx.Rollback()
if err := tx.QueryRowContext(r.Context(), `SELECT id FROM users WHERE id = $1 FOR UPDATE`, userID).Scan(new(string)); err != nil {
writeError(w, http.StatusInternalServerError, "could not register device")
return
}
var nonce []byte
var expiresAt time.Time
err = tx.QueryRowContext(r.Context(),
`SELECT nonce, expires_at FROM device_registration_challenges
WHERE id = $1 AND user_id = $2 AND consumed_at IS NULL FOR UPDATE`,
request.ChallengeID, userID,
).Scan(&nonce, &expiresAt)
if errors.Is(err, sql.ErrNoRows) || (err == nil && !time.Now().Before(expiresAt)) {
writeError(w, http.StatusBadRequest, "invalid or expired device registration challenge")
return
}
if err != nil {
writeError(w, http.StatusInternalServerError, "could not register device")
return
}
proofMessage := append([]byte("ee2e-device-registration-v1\x00"+request.ChallengeID+"\x00"), nonce...)
digest := sha256.Sum256(proofMessage)
if !ecdsa.VerifyASN1(publicKey, digest[:], signature) {
writeError(w, http.StatusBadRequest, "invalid device registration proof")
return
}
var activeDevices int
if err := tx.QueryRowContext(r.Context(),
`SELECT count(*) FROM devices WHERE user_id = $1 AND status = 'active'`, userID,
).Scan(&activeDevices); err != nil {
writeError(w, http.StatusInternalServerError, "could not register device")
return
}
if activeDevices >= maxActiveDevices {
writeError(w, http.StatusConflict, "device limit reached")
return
}
deviceID, err := newUUID()
if err != nil {
writeError(w, http.StatusInternalServerError, "could not register device")
return
}
if _, err := tx.ExecContext(r.Context(),
`UPDATE device_registration_challenges SET consumed_at = now() WHERE id = $1`, request.ChallengeID,
); err != nil {
writeError(w, http.StatusInternalServerError, "could not register device")
return
}
if _, err := tx.ExecContext(r.Context(),
`INSERT INTO devices(id, user_id, identity_public_key, status) VALUES ($1, $2, $3, 'active')`,
deviceID, userID, publicKeyDER,
); err != nil {
writeError(w, http.StatusConflict, "device key is already registered or invalid")
return
}
if err := tx.Commit(); err != nil {
writeError(w, http.StatusInternalServerError, "could not register device")
return
}
writeJSON(w, http.StatusCreated, map[string]string{
"device_id": deviceID,
"identity_key_type": "ecdsa-p256-sha256-v1",
"fingerprint": fingerprint(publicKeyDER),
})
}
func (s *apiServer) listDevices(w http.ResponseWriter, r *http.Request) {
username := r.PathValue("username")
if !usernamePattern.MatchString(username) {
writeError(w, http.StatusBadRequest, "invalid username")
return
}
rows, err := s.db.QueryContext(r.Context(),
`SELECT d.id::text, d.identity_public_key, d.created_at
FROM devices d JOIN users u ON u.id = d.user_id
WHERE u.username = $1 AND d.status = 'active' ORDER BY d.created_at, d.id`, username,
)
if err != nil {
writeError(w, http.StatusInternalServerError, "could not read device directory")
return
}
defer rows.Close()
devices := make([]directoryDevice, 0)
for rows.Next() {
var device directoryDevice
var publicKey []byte
if err := rows.Scan(&device.DeviceID, &publicKey, &device.CreatedAt); err != nil {
writeError(w, http.StatusInternalServerError, "could not read device directory")
return
}
device.IdentityKeyType = "ecdsa-p256-sha256-v1"
device.IdentityPublicKey = base64.StdEncoding.EncodeToString(publicKey)
device.Fingerprint = fingerprint(publicKey)
devices = append(devices, device)
}
if err := rows.Err(); err != nil {
writeError(w, http.StatusInternalServerError, "could not read device directory")
return
}
writeJSON(w, http.StatusOK, map[string]any{"username": username, "devices": devices})
}
func (s *apiServer) revokeDevice(w http.ResponseWriter, r *http.Request) {
deviceID := r.PathValue("deviceID")
if !uuidPattern.MatchString(deviceID) {
writeError(w, http.StatusBadRequest, "invalid device id")
return
}
userID := r.Context().Value(authenticatedUserIDKey).(string)
result, err := s.db.ExecContext(r.Context(),
`UPDATE devices SET status = 'revoked' WHERE id = $1 AND user_id = $2 AND status = 'active'`, deviceID, userID,
)
if err != nil {
writeError(w, http.StatusInternalServerError, "could not revoke device")
return
}
count, err := result.RowsAffected()
if err != nil {
writeError(w, http.StatusInternalServerError, "could not revoke device")
return
}
if count == 0 {
writeError(w, http.StatusNotFound, "device not found")
return
}
w.WriteHeader(http.StatusNoContent)
}
type authResponse struct {
UserID string `json:"user_id"`
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresAt time.Time `json:"expires_at"`
}
type directoryDevice struct {
DeviceID string `json:"device_id"`
IdentityKeyType string `json:"identity_key_type"`
IdentityPublicKey string `json:"identity_public_key"`
Fingerprint string `json:"fingerprint"`
CreatedAt time.Time `json:"created_at"`
}
func decodeJSON(w http.ResponseWriter, r *http.Request, destination any) bool {
r.Body = http.MaxBytesReader(w, r.Body, maxJSONBodyBytes)
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(destination); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON request")
return false
}
var extra any
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
writeError(w, http.StatusBadRequest, "invalid JSON request")
return false
}
return true
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func writeError(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, map[string]string{"error": message})
}
func newUUID() (string, error) {
bytes := make([]byte, 16)
if _, err := rand.Read(bytes); err != nil {
return "", err
}
bytes[6] = (bytes[6] & 0x0f) | 0x40
bytes[8] = (bytes[8] & 0x3f) | 0x80
encoded := hex.EncodeToString(bytes)
return fmt.Sprintf("%s-%s-%s-%s-%s", encoded[:8], encoded[8:12], encoded[12:16], encoded[16:20], encoded[20:]), nil
}
func newSessionToken() (string, [32]byte, error) {
var tokenHash [32]byte
bytes := make([]byte, 32)
if _, err := rand.Read(bytes); err != nil {
return "", tokenHash, err
}
tokenHash = sha256.Sum256(bytes)
return base64.RawURLEncoding.EncodeToString(bytes), tokenHash, nil
}
func fingerprint(publicKey []byte) string {
digest := sha256.Sum256(publicKey)
encoded := strings.ToUpper(hex.EncodeToString(digest[:]))
parts := make([]string, 0, len(encoded)/2)
for i := 0; i < len(encoded); i += 2 {
parts = append(parts, encoded[i:i+2])
}
return strings.Join(parts, ":")
}
const (
sessionLifetime = 30 * 24 * time.Hour
deviceChallengeLifetime = 5 * time.Minute
maxActiveDevices = 10
)
+108 -10
View File
@@ -1,28 +1,126 @@
package main package main
import ( import (
"encoding/json" "context"
"database/sql"
"embed"
"log" "log"
"net/http" "net/http"
"os" "os"
"strings"
"time" "time"
_ "github.com/jackc/pgx/v5/stdlib"
) )
//go:embed 001_auth_and_device_registration.sql
var migrationFS embed.FS
type apiServer struct {
db *sql.DB
passwords *passwordManager
}
func main() { func main() {
databaseURL := os.Getenv("DATABASE_URL")
if databaseURL == "" {
log.Fatal("DATABASE_URL is required")
}
db, err := sql.Open("pgx", databaseURL)
if err != nil {
log.Fatalf("open database: %v", err)
}
defer db.Close()
db.SetMaxOpenConns(20)
db.SetMaxIdleConns(5)
db.SetConnMaxIdleTime(5 * time.Minute)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := db.PingContext(ctx); err != nil {
log.Fatalf("connect to database: %v", err)
}
if err := applyMigrations(ctx, db); err != nil {
log.Fatalf("apply database migrations: %v", err)
}
passwords, err := newPasswordManager()
if err != nil {
log.Fatalf("initialize password hashing: %v", err)
}
app := &apiServer{db: db, passwords: passwords}
mux := http.NewServeMux() mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { mux.HandleFunc("GET /healthz", app.health)
w.Header().Set("Content-Type", "application/json") mux.HandleFunc("POST /api/v1/auth/register", app.register)
_ = json.NewEncoder(w).Encode(map[string]string{"status": "ok", "service": "api"}) mux.HandleFunc("POST /api/v1/auth/login", app.login)
}) mux.Handle("POST /api/v1/auth/logout", app.requireAuth(http.HandlerFunc(app.logout)))
// Placeholder only: registration/authentication is not implemented. mux.Handle("POST /api/v1/devices/challenges", app.requireAuth(http.HandlerFunc(app.createDeviceChallenge)))
mux.HandleFunc("POST /api/v1/auth/register", func(w http.ResponseWriter, r *http.Request) { mux.Handle("POST /api/v1/devices", app.requireAuth(http.HandlerFunc(app.registerDevice)))
http.Error(w, "registration not implemented", http.StatusNotImplemented) mux.Handle("DELETE /api/v1/devices/{deviceID}", app.requireAuth(http.HandlerFunc(app.revokeDevice)))
}) mux.Handle("GET /api/v1/directory/{username}/devices", app.requireAuth(http.HandlerFunc(app.listDevices)))
addr := os.Getenv("API_ADDR") addr := os.Getenv("API_ADDR")
if addr == "" { if addr == "" {
addr = ":8080" addr = ":8080"
} }
srv := &http.Server{Addr: addr, Handler: mux, ReadHeaderTimeout: 5 * time.Second} srv := &http.Server{
Addr: addr,
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
MaxHeaderBytes: 16 * 1024,
}
log.Printf("API listening on %s", addr) log.Printf("API listening on %s", addr)
log.Fatal(srv.ListenAndServe()) log.Fatal(srv.ListenAndServe())
} }
func applyMigrations(ctx context.Context, db *sql.DB) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS schema_migrations (
version INTEGER PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
)`); err != nil {
return err
}
var applied bool
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = 1)`).Scan(&applied); err != nil {
return err
}
if !applied {
migration, err := migrationFS.ReadFile("001_auth_and_device_registration.sql")
if err != nil {
return err
}
for _, statement := range strings.Split(string(migration), ";") {
statement = strings.TrimSpace(statement)
if statement == "" {
continue
}
if _, err := tx.ExecContext(ctx, statement); err != nil {
return err
}
}
if _, err := tx.ExecContext(ctx, `INSERT INTO schema_migrations(version) VALUES (1)`); err != nil {
return err
}
}
return tx.Commit()
}
func (s *apiServer) health(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if err := s.db.PingContext(ctx); err != nil {
writeError(w, http.StatusServiceUnavailable, "database unavailable")
return
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ok", "service": "api"})
}
+130
View File
@@ -0,0 +1,130 @@
package main
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strconv"
"strings"
"golang.org/x/crypto/argon2"
)
const (
argonTime uint32 = 3
argonMemory uint32 = 64 * 1024
argonThreads uint8 = 4
argonKeyLen uint32 = 32
argonSaltLen = 16
)
var errPasswordCapacity = errors.New("password hashing capacity reached")
type passwordManager struct {
workSlots chan struct{}
dummyHash string
}
func newPasswordManager() (*passwordManager, error) {
manager := &passwordManager{workSlots: make(chan struct{}, 2)}
salt := make([]byte, argonSaltLen)
if _, err := rand.Read(salt); err != nil {
return nil, err
}
manager.dummyHash = encodePasswordHash(argon2.IDKey([]byte("not-a-real-account-password"), salt, argonTime, argonMemory, argonThreads, argonKeyLen), salt)
return manager, nil
}
func (m *passwordManager) hash(password string) (string, error) {
if !m.acquire() {
return "", errPasswordCapacity
}
defer m.release()
salt := make([]byte, argonSaltLen)
if _, err := rand.Read(salt); err != nil {
return "", err
}
derived := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
return encodePasswordHash(derived, salt), nil
}
func (m *passwordManager) verify(password, encoded string) (bool, error) {
if !m.acquire() {
return false, errPasswordCapacity
}
defer m.release()
timeCost, memoryCost, threads, salt, expected, ok := parsePasswordHash(encoded)
if !ok {
return false, nil
}
actual := argon2.IDKey([]byte(password), salt, timeCost, memoryCost, threads, uint32(len(expected)))
return subtle.ConstantTimeCompare(actual, expected) == 1, nil
}
func (m *passwordManager) acquire() bool {
select {
case m.workSlots <- struct{}{}:
return true
default:
return false
}
}
func (m *passwordManager) release() {
<-m.workSlots
}
func encodePasswordHash(derived, salt []byte) string {
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
argon2.Version,
argonMemory,
argonTime,
argonThreads,
base64.RawStdEncoding.EncodeToString(salt),
base64.RawStdEncoding.EncodeToString(derived),
)
}
func parsePasswordHash(encoded string) (uint32, uint32, uint8, []byte, []byte, bool) {
parts := strings.Split(encoded, "$")
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" || parts[2] != "v=19" {
return 0, 0, 0, nil, nil, false
}
costs := strings.Split(parts[3], ",")
if len(costs) != 3 {
return 0, 0, 0, nil, nil, false
}
memory, err := parseCost(costs[0], "m=")
if err != nil {
return 0, 0, 0, nil, nil, false
}
timeCost, err := parseCost(costs[1], "t=")
if err != nil {
return 0, 0, 0, nil, nil, false
}
threads, err := parseCost(costs[2], "p=")
if err != nil ||
memory < 8*1024 || memory > 256*1024 || timeCost == 0 || timeCost > 10 || threads == 0 || threads > 16 {
return 0, 0, 0, nil, nil, false
}
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
if err != nil || len(salt) < 16 || len(salt) > 32 {
return 0, 0, 0, nil, nil, false
}
derived, err := base64.RawStdEncoding.DecodeString(parts[5])
if err != nil || len(derived) < 16 || len(derived) > 64 {
return 0, 0, 0, nil, nil, false
}
return timeCost, memory, uint8(threads), salt, derived, true
}
func parseCost(value, prefix string) (uint32, error) {
if !strings.HasPrefix(value, prefix) {
return 0, errors.New("invalid Argon2 cost parameter")
}
parsed, err := strconv.ParseUint(strings.TrimPrefix(value, prefix), 10, 32)
return uint32(parsed), err
}
+15 -1
View File
@@ -1,3 +1,17 @@
module github.com/ee2e-phone-calls/backend module github.com/ee2e-phone-calls/backend
go 1.23 go 1.26.0
require (
github.com/jackc/pgx/v5 v5.12.0
golang.org/x/crypto v0.59.0
)
require (
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.3 // indirect
golang.org/x/sync v0.25.0 // indirect
golang.org/x/sys v0.50.0 // indirect
golang.org/x/text v0.44.0 // indirect
)
+30
View File
@@ -0,0 +1,30 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.12.0 h1:hWwax8YiGT0YiN50U1oIDn5kgR7KC2tG3rmavwpPkxY=
github.com/jackc/pgx/v5 v5.12.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao=
github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+18
View File
@@ -0,0 +1,18 @@
# Android build versioning
The Android APK currently uses an app version plus a build identity:
- `versionName` defaults to `0.1.0+<git-short-sha>[-dirty]-<UTC epoch milliseconds>` (`local` is used when Git is unavailable). Dirty working trees are labeled; the timestamp makes repeated local builds distinct.
- `versionCode` defaults to the current UTC epoch seconds. Each second gets a new code, and the value remains within Android's supported range through 2038.
- `archiveDebugApk` copies the standard debug APK to `android/app/build/outputs/versioned-apk/ee2e-phone-calls-<version>-<build-id>-<version-code>-debug.apk`.
For CI and release builds, set explicit values so build records can be mapped to a commit and CI run. Gradle project properties take precedence over environment variables:
```bash
APP_VERSION=0.1.0 \
APP_BUILD_ID=abc1234-run47 \
APP_VERSION_CODE=47 \
gradle archiveDebugApk
```
The equivalent Gradle properties are `-PappVersion=0.1.0 -PappBuildId=abc1234-run47 -PappVersionCode=47`. Use a monotonically increasing positive `APP_VERSION_CODE` for published releases; Android uses it to order upgrades. The default build ID records the current Git revision, working-tree state, and build time. For CI, set it to the source revision and CI run. Generated APKs remain under Gradle's ignored `build/` directory and should be retained by the CI artifact store when needed.