Initial implementation of mcq — document reading queue
Single-binary service: push raw markdown via REST/gRPC API, read rendered HTML through mobile-friendly web UI. MCIAS auth on all endpoints, SQLite storage, goldmark rendering with GFM and syntax highlighting. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
23
internal/db/db.go
Normal file
23
internal/db/db.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
|
||||
mcdsldb "git.wntrmute.dev/mc/mcdsl/db"
|
||||
)
|
||||
|
||||
// DB wraps a SQLite database connection.
|
||||
type DB struct {
|
||||
*sql.DB
|
||||
}
|
||||
|
||||
// Open opens (or creates) a SQLite database at the given path with the
|
||||
// standard Metacircular pragmas: WAL mode, foreign keys, busy timeout.
|
||||
func Open(path string) (*DB, error) {
|
||||
sqlDB, err := mcdsldb.Open(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("db: %w", err)
|
||||
}
|
||||
return &DB{sqlDB}, nil
|
||||
}
|
||||
121
internal/db/documents.go
Normal file
121
internal/db/documents.go
Normal file
@@ -0,0 +1,121 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ErrNotFound is returned when a document does not exist.
|
||||
var ErrNotFound = errors.New("db: not found")
|
||||
|
||||
// Document represents a queued document.
|
||||
type Document struct {
|
||||
ID int64 `json:"id"`
|
||||
Slug string `json:"slug"`
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
PushedBy string `json:"pushed_by"`
|
||||
PushedAt string `json:"pushed_at"`
|
||||
Read bool `json:"read"`
|
||||
}
|
||||
|
||||
// ListDocuments returns all documents ordered by most recently pushed.
|
||||
func (d *DB) ListDocuments() ([]Document, error) {
|
||||
rows, err := d.Query(`SELECT id, slug, title, body, pushed_by, pushed_at, read FROM documents ORDER BY pushed_at DESC`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var docs []Document
|
||||
for rows.Next() {
|
||||
var doc Document
|
||||
if err := rows.Scan(&doc.ID, &doc.Slug, &doc.Title, &doc.Body, &doc.PushedBy, &doc.PushedAt, &doc.Read); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
docs = append(docs, doc)
|
||||
}
|
||||
return docs, rows.Err()
|
||||
}
|
||||
|
||||
// GetDocument returns a single document by slug.
|
||||
func (d *DB) GetDocument(slug string) (*Document, error) {
|
||||
var doc Document
|
||||
err := d.QueryRow(
|
||||
`SELECT id, slug, title, body, pushed_by, pushed_at, read FROM documents WHERE slug = ?`,
|
||||
slug,
|
||||
).Scan(&doc.ID, &doc.Slug, &doc.Title, &doc.Body, &doc.PushedBy, &doc.PushedAt, &doc.Read)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &doc, nil
|
||||
}
|
||||
|
||||
// PutDocument creates or updates a document by slug (upsert).
|
||||
func (d *DB) PutDocument(slug, title, body, pushedBy string) (*Document, error) {
|
||||
now := time.Now().UTC().Format(time.RFC3339)
|
||||
_, err := d.Exec(`
|
||||
INSERT INTO documents (slug, title, body, pushed_by, pushed_at, read)
|
||||
VALUES (?, ?, ?, ?, ?, 0)
|
||||
ON CONFLICT(slug) DO UPDATE SET
|
||||
title = excluded.title,
|
||||
body = excluded.body,
|
||||
pushed_by = excluded.pushed_by,
|
||||
pushed_at = excluded.pushed_at,
|
||||
read = 0`,
|
||||
slug, title, body, pushedBy, now,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return d.GetDocument(slug)
|
||||
}
|
||||
|
||||
// DeleteDocument removes a document by slug.
|
||||
func (d *DB) DeleteDocument(slug string) error {
|
||||
res, err := d.Exec(`DELETE FROM documents WHERE slug = ?`, slug)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarkRead sets the read flag on a document.
|
||||
func (d *DB) MarkRead(slug string) (*Document, error) {
|
||||
return d.setRead(slug, true)
|
||||
}
|
||||
|
||||
// MarkUnread clears the read flag on a document.
|
||||
func (d *DB) MarkUnread(slug string) (*Document, error) {
|
||||
return d.setRead(slug, false)
|
||||
}
|
||||
|
||||
func (d *DB) setRead(slug string, read bool) (*Document, error) {
|
||||
val := 0
|
||||
if read {
|
||||
val = 1
|
||||
}
|
||||
res, err := d.Exec(`UPDATE documents SET read = ? WHERE slug = ?`, val, slug)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n, err := res.RowsAffected()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n == 0 {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return d.GetDocument(slug)
|
||||
}
|
||||
145
internal/db/documents_test.go
Normal file
145
internal/db/documents_test.go
Normal file
@@ -0,0 +1,145 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func openTestDB(t *testing.T) *DB {
|
||||
t.Helper()
|
||||
dbPath := filepath.Join(t.TempDir(), "test.db")
|
||||
database, err := Open(dbPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := database.Migrate(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { database.Close() })
|
||||
return database
|
||||
}
|
||||
|
||||
func TestPutAndGetDocument(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
|
||||
doc, err := db.PutDocument("test-slug", "Test Title", "# Hello", "kyle")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if doc.Slug != "test-slug" {
|
||||
t.Errorf("slug = %q, want %q", doc.Slug, "test-slug")
|
||||
}
|
||||
if doc.Title != "Test Title" {
|
||||
t.Errorf("title = %q, want %q", doc.Title, "Test Title")
|
||||
}
|
||||
if doc.Body != "# Hello" {
|
||||
t.Errorf("body = %q, want %q", doc.Body, "# Hello")
|
||||
}
|
||||
if doc.PushedBy != "kyle" {
|
||||
t.Errorf("pushed_by = %q, want %q", doc.PushedBy, "kyle")
|
||||
}
|
||||
if doc.Read {
|
||||
t.Error("new document should not be read")
|
||||
}
|
||||
|
||||
got, err := db.GetDocument("test-slug")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Title != "Test Title" {
|
||||
t.Errorf("got title = %q, want %q", got.Title, "Test Title")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPutDocumentUpsert(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
|
||||
_, err := db.PutDocument("slug", "V1", "body v1", "alice")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Mark as read.
|
||||
_, err = db.MarkRead("slug")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Upsert — should replace and reset read flag.
|
||||
doc, err := db.PutDocument("slug", "V2", "body v2", "bob")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if doc.Title != "V2" {
|
||||
t.Errorf("title = %q, want V2", doc.Title)
|
||||
}
|
||||
if doc.Body != "body v2" {
|
||||
t.Errorf("body = %q, want body v2", doc.Body)
|
||||
}
|
||||
if doc.PushedBy != "bob" {
|
||||
t.Errorf("pushed_by = %q, want bob", doc.PushedBy)
|
||||
}
|
||||
if doc.Read {
|
||||
t.Error("upsert should reset read flag")
|
||||
}
|
||||
}
|
||||
|
||||
func TestListDocuments(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
|
||||
_, _ = db.PutDocument("a", "A", "body", "user")
|
||||
_, _ = db.PutDocument("b", "B", "body", "user")
|
||||
|
||||
docs, err := db.ListDocuments()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(docs) != 2 {
|
||||
t.Fatalf("got %d docs, want 2", len(docs))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteDocument(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
|
||||
_, _ = db.PutDocument("del", "Del", "body", "user")
|
||||
if err := db.DeleteDocument("del"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, err := db.GetDocument("del")
|
||||
if err != ErrNotFound {
|
||||
t.Errorf("got err = %v, want ErrNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteDocumentNotFound(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
|
||||
err := db.DeleteDocument("nope")
|
||||
if err != ErrNotFound {
|
||||
t.Errorf("got err = %v, want ErrNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarkReadUnread(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
|
||||
_, _ = db.PutDocument("rw", "RW", "body", "user")
|
||||
|
||||
doc, err := db.MarkRead("rw")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !doc.Read {
|
||||
t.Error("expected read=true after MarkRead")
|
||||
}
|
||||
|
||||
doc, err = db.MarkUnread("rw")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if doc.Read {
|
||||
t.Error("expected read=false after MarkUnread")
|
||||
}
|
||||
}
|
||||
28
internal/db/migrate.go
Normal file
28
internal/db/migrate.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
mcdsldb "git.wntrmute.dev/mc/mcdsl/db"
|
||||
)
|
||||
|
||||
// Migrations is the ordered list of MCQ schema migrations.
|
||||
var Migrations = []mcdsldb.Migration{
|
||||
{
|
||||
Version: 1,
|
||||
Name: "documents",
|
||||
SQL: `
|
||||
CREATE TABLE IF NOT EXISTS documents (
|
||||
id INTEGER PRIMARY KEY,
|
||||
slug TEXT NOT NULL UNIQUE,
|
||||
title TEXT NOT NULL,
|
||||
body TEXT NOT NULL,
|
||||
pushed_by TEXT NOT NULL,
|
||||
pushed_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
|
||||
read INTEGER NOT NULL DEFAULT 0
|
||||
);`,
|
||||
},
|
||||
}
|
||||
|
||||
// Migrate applies all pending migrations.
|
||||
func (d *DB) Migrate() error {
|
||||
return mcdsldb.Migrate(d.DB, Migrations)
|
||||
}
|
||||
20
internal/grpcserver/admin.go
Normal file
20
internal/grpcserver/admin.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package grpcserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
pb "git.wntrmute.dev/mc/mcq/gen/mcq/v1"
|
||||
"git.wntrmute.dev/mc/mcq/internal/db"
|
||||
)
|
||||
|
||||
type adminService struct {
|
||||
pb.UnimplementedAdminServiceServer
|
||||
db *db.DB
|
||||
}
|
||||
|
||||
func (s *adminService) Health(_ context.Context, _ *pb.HealthRequest) (*pb.HealthResponse, error) {
|
||||
if err := s.db.Ping(); err != nil {
|
||||
return &pb.HealthResponse{Status: "unhealthy"}, nil
|
||||
}
|
||||
return &pb.HealthResponse{Status: "ok"}, nil
|
||||
}
|
||||
38
internal/grpcserver/auth_handler.go
Normal file
38
internal/grpcserver/auth_handler.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package grpcserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
mcdslauth "git.wntrmute.dev/mc/mcdsl/auth"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
pb "git.wntrmute.dev/mc/mcq/gen/mcq/v1"
|
||||
)
|
||||
|
||||
type authService struct {
|
||||
pb.UnimplementedAuthServiceServer
|
||||
auth *mcdslauth.Authenticator
|
||||
}
|
||||
|
||||
func (s *authService) Login(_ context.Context, req *pb.LoginRequest) (*pb.LoginResponse, error) {
|
||||
token, _, err := s.auth.Login(req.Username, req.Password, req.TotpCode)
|
||||
if err != nil {
|
||||
if errors.Is(err, mcdslauth.ErrInvalidCredentials) {
|
||||
return nil, status.Error(codes.Unauthenticated, "invalid credentials")
|
||||
}
|
||||
if errors.Is(err, mcdslauth.ErrForbidden) {
|
||||
return nil, status.Error(codes.PermissionDenied, "access denied by login policy")
|
||||
}
|
||||
return nil, status.Error(codes.Unavailable, "authentication service unavailable")
|
||||
}
|
||||
return &pb.LoginResponse{Token: token}, nil
|
||||
}
|
||||
|
||||
func (s *authService) Logout(_ context.Context, req *pb.LogoutRequest) (*pb.LogoutResponse, error) {
|
||||
if err := s.auth.Logout(req.Token); err != nil {
|
||||
return nil, status.Error(codes.Internal, "logout failed")
|
||||
}
|
||||
return &pb.LogoutResponse{}, nil
|
||||
}
|
||||
140
internal/grpcserver/documents.go
Normal file
140
internal/grpcserver/documents.go
Normal file
@@ -0,0 +1,140 @@
|
||||
package grpcserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
|
||||
mcdslgrpc "git.wntrmute.dev/mc/mcdsl/grpcserver"
|
||||
|
||||
pb "git.wntrmute.dev/mc/mcq/gen/mcq/v1"
|
||||
"git.wntrmute.dev/mc/mcq/internal/db"
|
||||
)
|
||||
|
||||
type documentService struct {
|
||||
pb.UnimplementedDocumentServiceServer
|
||||
db *db.DB
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func (s *documentService) ListDocuments(_ context.Context, _ *pb.ListDocumentsRequest) (*pb.ListDocumentsResponse, error) {
|
||||
docs, err := s.db.ListDocuments()
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Internal, "failed to list documents")
|
||||
}
|
||||
|
||||
resp := &pb.ListDocumentsResponse{}
|
||||
for _, d := range docs {
|
||||
resp.Documents = append(resp.Documents, s.docToProto(d))
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (s *documentService) GetDocument(_ context.Context, req *pb.GetDocumentRequest) (*pb.Document, error) {
|
||||
if req.Slug == "" {
|
||||
return nil, status.Error(codes.InvalidArgument, "slug is required")
|
||||
}
|
||||
|
||||
doc, err := s.db.GetDocument(req.Slug)
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
return nil, status.Error(codes.NotFound, "document not found")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Internal, "failed to get document")
|
||||
}
|
||||
return s.docToProto(*doc), nil
|
||||
}
|
||||
|
||||
func (s *documentService) PutDocument(ctx context.Context, req *pb.PutDocumentRequest) (*pb.Document, error) {
|
||||
if req.Slug == "" {
|
||||
return nil, status.Error(codes.InvalidArgument, "slug is required")
|
||||
}
|
||||
if req.Title == "" {
|
||||
return nil, status.Error(codes.InvalidArgument, "title is required")
|
||||
}
|
||||
if req.Body == "" {
|
||||
return nil, status.Error(codes.InvalidArgument, "body is required")
|
||||
}
|
||||
|
||||
pushedBy := "unknown"
|
||||
if info := mcdslgrpc.TokenInfoFromContext(ctx); info != nil {
|
||||
pushedBy = info.Username
|
||||
}
|
||||
|
||||
doc, err := s.db.PutDocument(req.Slug, req.Title, req.Body, pushedBy)
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Internal, "failed to save document")
|
||||
}
|
||||
return s.docToProto(*doc), nil
|
||||
}
|
||||
|
||||
func (s *documentService) DeleteDocument(_ context.Context, req *pb.DeleteDocumentRequest) (*pb.DeleteDocumentResponse, error) {
|
||||
if req.Slug == "" {
|
||||
return nil, status.Error(codes.InvalidArgument, "slug is required")
|
||||
}
|
||||
|
||||
err := s.db.DeleteDocument(req.Slug)
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
return nil, status.Error(codes.NotFound, "document not found")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Internal, "failed to delete document")
|
||||
}
|
||||
return &pb.DeleteDocumentResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *documentService) MarkRead(_ context.Context, req *pb.MarkReadRequest) (*pb.Document, error) {
|
||||
if req.Slug == "" {
|
||||
return nil, status.Error(codes.InvalidArgument, "slug is required")
|
||||
}
|
||||
|
||||
doc, err := s.db.MarkRead(req.Slug)
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
return nil, status.Error(codes.NotFound, "document not found")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Internal, "failed to mark read")
|
||||
}
|
||||
return s.docToProto(*doc), nil
|
||||
}
|
||||
|
||||
func (s *documentService) MarkUnread(_ context.Context, req *pb.MarkUnreadRequest) (*pb.Document, error) {
|
||||
if req.Slug == "" {
|
||||
return nil, status.Error(codes.InvalidArgument, "slug is required")
|
||||
}
|
||||
|
||||
doc, err := s.db.MarkUnread(req.Slug)
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
return nil, status.Error(codes.NotFound, "document not found")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, status.Error(codes.Internal, "failed to mark unread")
|
||||
}
|
||||
return s.docToProto(*doc), nil
|
||||
}
|
||||
|
||||
func (s *documentService) docToProto(d db.Document) *pb.Document {
|
||||
return &pb.Document{
|
||||
Id: d.ID,
|
||||
Slug: d.Slug,
|
||||
Title: d.Title,
|
||||
Body: d.Body,
|
||||
PushedBy: d.PushedBy,
|
||||
PushedAt: s.parseTimestamp(d.PushedAt),
|
||||
Read: d.Read,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *documentService) parseTimestamp(v string) *timestamppb.Timestamp {
|
||||
t, err := time.Parse(time.RFC3339, v)
|
||||
if err != nil {
|
||||
s.logger.Warn("failed to parse timestamp", "value", v, "error", err)
|
||||
return nil
|
||||
}
|
||||
return timestamppb.New(t)
|
||||
}
|
||||
40
internal/grpcserver/interceptors.go
Normal file
40
internal/grpcserver/interceptors.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package grpcserver
|
||||
|
||||
import (
|
||||
mcdslgrpc "git.wntrmute.dev/mc/mcdsl/grpcserver"
|
||||
)
|
||||
|
||||
// methodMap builds the mcdsl grpcserver.MethodMap for MCQ.
|
||||
//
|
||||
// Adding a new RPC without adding it to the correct map is a security
|
||||
// defect — the mcdsl auth interceptor denies unmapped methods by default.
|
||||
func methodMap() mcdslgrpc.MethodMap {
|
||||
return mcdslgrpc.MethodMap{
|
||||
Public: publicMethods(),
|
||||
AuthRequired: authRequiredMethods(),
|
||||
AdminRequired: adminRequiredMethods(),
|
||||
}
|
||||
}
|
||||
|
||||
func publicMethods() map[string]bool {
|
||||
return map[string]bool{
|
||||
"/mcq.v1.AdminService/Health": true,
|
||||
"/mcq.v1.AuthService/Login": true,
|
||||
}
|
||||
}
|
||||
|
||||
func authRequiredMethods() map[string]bool {
|
||||
return map[string]bool{
|
||||
"/mcq.v1.AuthService/Logout": true,
|
||||
"/mcq.v1.DocumentService/ListDocuments": true,
|
||||
"/mcq.v1.DocumentService/GetDocument": true,
|
||||
"/mcq.v1.DocumentService/PutDocument": true,
|
||||
"/mcq.v1.DocumentService/DeleteDocument": true,
|
||||
"/mcq.v1.DocumentService/MarkRead": true,
|
||||
"/mcq.v1.DocumentService/MarkUnread": true,
|
||||
}
|
||||
}
|
||||
|
||||
func adminRequiredMethods() map[string]bool {
|
||||
return map[string]bool{}
|
||||
}
|
||||
49
internal/grpcserver/server.go
Normal file
49
internal/grpcserver/server.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package grpcserver
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net"
|
||||
|
||||
mcdslauth "git.wntrmute.dev/mc/mcdsl/auth"
|
||||
mcdslgrpc "git.wntrmute.dev/mc/mcdsl/grpcserver"
|
||||
|
||||
pb "git.wntrmute.dev/mc/mcq/gen/mcq/v1"
|
||||
"git.wntrmute.dev/mc/mcq/internal/db"
|
||||
)
|
||||
|
||||
// Deps holds the dependencies injected into the gRPC server.
|
||||
type Deps struct {
|
||||
DB *db.DB
|
||||
Authenticator *mcdslauth.Authenticator
|
||||
}
|
||||
|
||||
// Server wraps a mcdsl grpcserver.Server with MCQ-specific services.
|
||||
type Server struct {
|
||||
srv *mcdslgrpc.Server
|
||||
}
|
||||
|
||||
// New creates a configured gRPC server with MCQ services registered.
|
||||
func New(certFile, keyFile string, deps Deps, logger *slog.Logger) (*Server, error) {
|
||||
srv, err := mcdslgrpc.New(certFile, keyFile, deps.Authenticator, methodMap(), logger, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s := &Server{srv: srv}
|
||||
|
||||
pb.RegisterAdminServiceServer(srv.GRPCServer, &adminService{db: deps.DB})
|
||||
pb.RegisterAuthServiceServer(srv.GRPCServer, &authService{auth: deps.Authenticator})
|
||||
pb.RegisterDocumentServiceServer(srv.GRPCServer, &documentService{db: deps.DB, logger: logger})
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Serve starts the gRPC server on the given listener.
|
||||
func (s *Server) Serve(lis net.Listener) error {
|
||||
return s.srv.GRPCServer.Serve(lis)
|
||||
}
|
||||
|
||||
// GracefulStop gracefully stops the gRPC server.
|
||||
func (s *Server) GracefulStop() {
|
||||
s.srv.Stop()
|
||||
}
|
||||
50
internal/render/render.go
Normal file
50
internal/render/render.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package render
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
|
||||
chromahtml "github.com/alecthomas/chroma/v2/formatters/html"
|
||||
"github.com/yuin/goldmark"
|
||||
highlighting "github.com/yuin/goldmark-highlighting/v2"
|
||||
"github.com/yuin/goldmark/extension"
|
||||
"github.com/yuin/goldmark/parser"
|
||||
"github.com/yuin/goldmark/renderer/html"
|
||||
)
|
||||
|
||||
// Renderer converts markdown to HTML using goldmark.
|
||||
type Renderer struct {
|
||||
md goldmark.Markdown
|
||||
}
|
||||
|
||||
// New creates a Renderer with GFM, syntax highlighting, and heading anchors.
|
||||
func New() *Renderer {
|
||||
md := goldmark.New(
|
||||
goldmark.WithExtensions(
|
||||
extension.GFM,
|
||||
highlighting.NewHighlighting(
|
||||
highlighting.WithStyle("github"),
|
||||
highlighting.WithFormatOptions(
|
||||
chromahtml.WithClasses(true),
|
||||
),
|
||||
),
|
||||
),
|
||||
goldmark.WithParserOptions(
|
||||
parser.WithAutoHeadingID(),
|
||||
),
|
||||
goldmark.WithRendererOptions(
|
||||
html.WithUnsafe(),
|
||||
),
|
||||
)
|
||||
|
||||
return &Renderer{md: md}
|
||||
}
|
||||
|
||||
// Render converts markdown source to HTML.
|
||||
func (r *Renderer) Render(source []byte) (string, error) {
|
||||
var buf bytes.Buffer
|
||||
if err := r.md.Convert(source, &buf); err != nil {
|
||||
return "", fmt.Errorf("render markdown: %w", err)
|
||||
}
|
||||
return buf.String(), nil
|
||||
}
|
||||
62
internal/server/auth.go
Normal file
62
internal/server/auth.go
Normal file
@@ -0,0 +1,62 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
mcdslauth "git.wntrmute.dev/mc/mcdsl/auth"
|
||||
)
|
||||
|
||||
type loginRequest struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
TOTPCode string `json:"totp_code"`
|
||||
}
|
||||
|
||||
type loginResponse struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
func loginHandler(auth *mcdslauth.Authenticator) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var req loginRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
token, _, err := auth.Login(req.Username, req.Password, req.TOTPCode)
|
||||
if err != nil {
|
||||
if errors.Is(err, mcdslauth.ErrInvalidCredentials) {
|
||||
writeError(w, http.StatusUnauthorized, "invalid credentials")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, mcdslauth.ErrForbidden) {
|
||||
writeError(w, http.StatusForbidden, "access denied by login policy")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusServiceUnavailable, "authentication service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, loginResponse{Token: token})
|
||||
}
|
||||
}
|
||||
|
||||
func logoutHandler(auth *mcdslauth.Authenticator) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
token := extractBearerToken(r)
|
||||
if token == "" {
|
||||
writeError(w, http.StatusUnauthorized, "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
if err := auth.Logout(token); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "logout failed")
|
||||
return
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
131
internal/server/documents.go
Normal file
131
internal/server/documents.go
Normal file
@@ -0,0 +1,131 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"git.wntrmute.dev/mc/mcq/internal/db"
|
||||
)
|
||||
|
||||
type putDocumentRequest struct {
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
}
|
||||
|
||||
func listDocumentsHandler(database *db.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, _ *http.Request) {
|
||||
docs, err := database.ListDocuments()
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to list documents")
|
||||
return
|
||||
}
|
||||
if docs == nil {
|
||||
docs = []db.Document{}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"documents": docs})
|
||||
}
|
||||
}
|
||||
|
||||
func getDocumentHandler(database *db.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
slug := chi.URLParam(r, "slug")
|
||||
doc, err := database.GetDocument(slug)
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
writeError(w, http.StatusNotFound, "document not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to get document")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, doc)
|
||||
}
|
||||
}
|
||||
|
||||
func putDocumentHandler(database *db.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
slug := chi.URLParam(r, "slug")
|
||||
|
||||
var req putDocumentRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
|
||||
if req.Title == "" {
|
||||
writeError(w, http.StatusBadRequest, "title is required")
|
||||
return
|
||||
}
|
||||
if req.Body == "" {
|
||||
writeError(w, http.StatusBadRequest, "body is required")
|
||||
return
|
||||
}
|
||||
|
||||
info := tokenInfoFromContext(r.Context())
|
||||
pushedBy := "unknown"
|
||||
if info != nil {
|
||||
pushedBy = info.Username
|
||||
}
|
||||
|
||||
doc, err := database.PutDocument(slug, req.Title, req.Body, pushedBy)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to save document")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, doc)
|
||||
}
|
||||
}
|
||||
|
||||
func deleteDocumentHandler(database *db.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
slug := chi.URLParam(r, "slug")
|
||||
|
||||
err := database.DeleteDocument(slug)
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
writeError(w, http.StatusNotFound, "document not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to delete document")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func markReadHandler(database *db.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
slug := chi.URLParam(r, "slug")
|
||||
|
||||
doc, err := database.MarkRead(slug)
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
writeError(w, http.StatusNotFound, "document not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to mark read")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, doc)
|
||||
}
|
||||
}
|
||||
|
||||
func markUnreadHandler(database *db.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
slug := chi.URLParam(r, "slug")
|
||||
|
||||
doc, err := database.MarkUnread(slug)
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
writeError(w, http.StatusNotFound, "document not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "failed to mark unread")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, doc)
|
||||
}
|
||||
}
|
||||
84
internal/server/middleware.go
Normal file
84
internal/server/middleware.go
Normal file
@@ -0,0 +1,84 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
mcdslauth "git.wntrmute.dev/mc/mcdsl/auth"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const tokenInfoKey contextKey = "tokenInfo"
|
||||
|
||||
// requireAuth returns middleware that validates Bearer tokens via MCIAS.
|
||||
func requireAuth(auth *mcdslauth.Authenticator) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
token := extractBearerToken(r)
|
||||
if token == "" {
|
||||
writeError(w, http.StatusUnauthorized, "authentication required")
|
||||
return
|
||||
}
|
||||
|
||||
info, err := auth.ValidateToken(token)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusUnauthorized, "invalid or expired token")
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), tokenInfoKey, info)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// tokenInfoFromContext extracts the TokenInfo from the request context.
|
||||
func tokenInfoFromContext(ctx context.Context) *mcdslauth.TokenInfo {
|
||||
info, _ := ctx.Value(tokenInfoKey).(*mcdslauth.TokenInfo)
|
||||
return info
|
||||
}
|
||||
|
||||
// extractBearerToken extracts a bearer token from the Authorization header.
|
||||
func extractBearerToken(r *http.Request) string {
|
||||
h := r.Header.Get("Authorization")
|
||||
if h == "" {
|
||||
return ""
|
||||
}
|
||||
const prefix = "Bearer "
|
||||
if !strings.HasPrefix(h, prefix) {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(h[len(prefix):])
|
||||
}
|
||||
|
||||
// loggingMiddleware logs HTTP requests.
|
||||
func loggingMiddleware(logger *slog.Logger) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(sw, r)
|
||||
logger.Info("http",
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", sw.status,
|
||||
"duration", time.Since(start),
|
||||
"remote", r.RemoteAddr,
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (w *statusWriter) WriteHeader(code int) {
|
||||
w.status = code
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
54
internal/server/routes.go
Normal file
54
internal/server/routes.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
mcdslauth "git.wntrmute.dev/mc/mcdsl/auth"
|
||||
"git.wntrmute.dev/mc/mcdsl/health"
|
||||
|
||||
"git.wntrmute.dev/mc/mcq/internal/db"
|
||||
)
|
||||
|
||||
// Deps holds dependencies injected into the REST handlers.
|
||||
type Deps struct {
|
||||
DB *db.DB
|
||||
Auth *mcdslauth.Authenticator
|
||||
Logger *slog.Logger
|
||||
}
|
||||
|
||||
// RegisterRoutes adds all MCQ REST endpoints to the given router.
|
||||
func RegisterRoutes(r chi.Router, deps Deps) {
|
||||
// Public endpoints.
|
||||
r.Post("/v1/auth/login", loginHandler(deps.Auth))
|
||||
r.Get("/v1/health", health.Handler(deps.DB.DB))
|
||||
|
||||
// Authenticated endpoints.
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(requireAuth(deps.Auth))
|
||||
|
||||
r.Post("/v1/auth/logout", logoutHandler(deps.Auth))
|
||||
|
||||
r.Get("/v1/documents", listDocumentsHandler(deps.DB))
|
||||
r.Get("/v1/documents/{slug}", getDocumentHandler(deps.DB))
|
||||
r.Put("/v1/documents/{slug}", putDocumentHandler(deps.DB))
|
||||
r.Delete("/v1/documents/{slug}", deleteDocumentHandler(deps.DB))
|
||||
r.Post("/v1/documents/{slug}/read", markReadHandler(deps.DB))
|
||||
r.Post("/v1/documents/{slug}/unread", markUnreadHandler(deps.DB))
|
||||
})
|
||||
}
|
||||
|
||||
// writeJSON writes a JSON response with the given status code.
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
// writeError writes a standard error response.
|
||||
func writeError(w http.ResponseWriter, status int, message string) {
|
||||
writeJSON(w, status, map[string]string{"error": message})
|
||||
}
|
||||
178
internal/webserver/server.go
Normal file
178
internal/webserver/server.go
Normal file
@@ -0,0 +1,178 @@
|
||||
package webserver
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"git.wntrmute.dev/mc/mcdsl/auth"
|
||||
"git.wntrmute.dev/mc/mcdsl/csrf"
|
||||
"git.wntrmute.dev/mc/mcdsl/web"
|
||||
|
||||
mcqweb "git.wntrmute.dev/mc/mcq/web"
|
||||
|
||||
"git.wntrmute.dev/mc/mcq/internal/db"
|
||||
"git.wntrmute.dev/mc/mcq/internal/render"
|
||||
)
|
||||
|
||||
const cookieName = "mcq_session"
|
||||
|
||||
// Config holds webserver-specific configuration.
|
||||
type Config struct {
|
||||
ServiceName string
|
||||
Tags []string
|
||||
}
|
||||
|
||||
// Server is the MCQ web UI server.
|
||||
type Server struct {
|
||||
db *db.DB
|
||||
auth *auth.Authenticator
|
||||
csrf *csrf.Protect
|
||||
render *render.Renderer
|
||||
logger *slog.Logger
|
||||
config Config
|
||||
}
|
||||
|
||||
// New creates a web UI server.
|
||||
func New(cfg Config, database *db.DB, authenticator *auth.Authenticator, logger *slog.Logger) (*Server, error) {
|
||||
csrfSecret := make([]byte, 32)
|
||||
if _, err := rand.Read(csrfSecret); err != nil {
|
||||
return nil, fmt.Errorf("generate CSRF secret: %w", err)
|
||||
}
|
||||
csrfProtect := csrf.New(csrfSecret, "_csrf", "csrf_token")
|
||||
|
||||
return &Server{
|
||||
db: database,
|
||||
auth: authenticator,
|
||||
csrf: csrfProtect,
|
||||
render: render.New(),
|
||||
logger: logger,
|
||||
config: cfg,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RegisterRoutes adds web UI routes to the given router.
|
||||
func (s *Server) RegisterRoutes(r chi.Router) {
|
||||
r.Get("/login", s.handleLoginPage)
|
||||
r.Post("/login", s.csrf.Middleware(http.HandlerFunc(s.handleLogin)).ServeHTTP)
|
||||
r.Get("/static/*", http.FileServer(http.FS(mcqweb.FS)).ServeHTTP)
|
||||
|
||||
// Authenticated routes.
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(web.RequireAuth(s.auth, cookieName, "/login"))
|
||||
r.Use(s.csrf.Middleware)
|
||||
|
||||
r.Get("/", s.handleList)
|
||||
r.Get("/d/{slug}", s.handleRead)
|
||||
r.Post("/d/{slug}/read", s.handleMarkRead)
|
||||
r.Post("/d/{slug}/unread", s.handleMarkUnread)
|
||||
r.Post("/logout", s.handleLogout)
|
||||
})
|
||||
}
|
||||
|
||||
type pageData struct {
|
||||
Username string
|
||||
Error string
|
||||
Title string
|
||||
Content any
|
||||
}
|
||||
|
||||
func (s *Server) handleLoginPage(w http.ResponseWriter, r *http.Request) {
|
||||
web.RenderTemplate(w, mcqweb.FS, "login.html", pageData{}, s.csrf.TemplateFunc(w))
|
||||
}
|
||||
|
||||
func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
username := r.FormValue("username")
|
||||
password := r.FormValue("password")
|
||||
totpCode := r.FormValue("totp_code")
|
||||
|
||||
token, _, err := s.auth.Login(username, password, totpCode)
|
||||
if err != nil {
|
||||
web.RenderTemplate(w, mcqweb.FS, "login.html", pageData{Error: "Invalid credentials"}, s.csrf.TemplateFunc(w))
|
||||
return
|
||||
}
|
||||
|
||||
web.SetSessionCookie(w, cookieName, token)
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
}
|
||||
|
||||
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
|
||||
token := web.GetSessionToken(r, cookieName)
|
||||
if token != "" {
|
||||
_ = s.auth.Logout(token)
|
||||
}
|
||||
web.ClearSessionCookie(w, cookieName)
|
||||
http.Redirect(w, r, "/login", http.StatusFound)
|
||||
}
|
||||
|
||||
type listData struct {
|
||||
Username string
|
||||
Documents []db.Document
|
||||
}
|
||||
|
||||
func (s *Server) handleList(w http.ResponseWriter, r *http.Request) {
|
||||
info := auth.TokenInfoFromContext(r.Context())
|
||||
docs, err := s.db.ListDocuments()
|
||||
if err != nil {
|
||||
s.logger.Error("failed to list documents", "error", err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if docs == nil {
|
||||
docs = []db.Document{}
|
||||
}
|
||||
web.RenderTemplate(w, mcqweb.FS, "list.html", listData{
|
||||
Username: info.Username,
|
||||
Documents: docs,
|
||||
}, s.csrf.TemplateFunc(w))
|
||||
}
|
||||
|
||||
type readData struct {
|
||||
Username string
|
||||
Doc db.Document
|
||||
HTML template.HTML
|
||||
}
|
||||
|
||||
func (s *Server) handleRead(w http.ResponseWriter, r *http.Request) {
|
||||
info := auth.TokenInfoFromContext(r.Context())
|
||||
slug := chi.URLParam(r, "slug")
|
||||
|
||||
doc, err := s.db.GetDocument(slug)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
html, err := s.render.Render([]byte(doc.Body))
|
||||
if err != nil {
|
||||
s.logger.Error("failed to render markdown", "slug", slug, "error", err)
|
||||
http.Error(w, "render error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
web.RenderTemplate(w, mcqweb.FS, "read.html", readData{
|
||||
Username: info.Username,
|
||||
Doc: *doc,
|
||||
HTML: template.HTML(html), //nolint:gosec // markdown rendered by goldmark, not user-controlled injection
|
||||
}, s.csrf.TemplateFunc(w))
|
||||
}
|
||||
|
||||
func (s *Server) handleMarkRead(w http.ResponseWriter, r *http.Request) {
|
||||
slug := chi.URLParam(r, "slug")
|
||||
if _, err := s.db.MarkRead(slug); err != nil {
|
||||
s.logger.Error("failed to mark read", "slug", slug, "error", err)
|
||||
}
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
}
|
||||
|
||||
func (s *Server) handleMarkUnread(w http.ResponseWriter, r *http.Request) {
|
||||
slug := chi.URLParam(r, "slug")
|
||||
if _, err := s.db.MarkUnread(slug); err != nil {
|
||||
s.logger.Error("failed to mark unread", "slug", slug, "error", err)
|
||||
}
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
}
|
||||
Reference in New Issue
Block a user