A person leaves licences out, and no key of theirs reaches a model under one
CI / test (push) Successful in 11m28s

A game sold in the EU cannot ship what a licence excluding the EU made. On
the profile page a person leaves out licences one by one, or by rule:
every licence forbidding commercial use, every licence granting nothing in
a region. The rules cover models added later. The choice reaches every
principal through the resolved limits, so permits() leaves such models out
of /v1/models, requests, jobs, fallbacks and the portal's pickers, and a
request for one is refused 403 licence_excluded saying which choice did.

Kept in user_excluded_licences (migration 0046), copied with the store and
gone with the person.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ilker ManapandClaude Opus 5.5 committed 2026-10-11 16:10:22 +02:00
1 parent a313b3e0da
commit 4bbac0833d
20 files changed
+658 -7

No files matched your search

+14 -3
View File
@@ -95,9 +95,13 @@ type AccountPages struct {
hasSettings bool
// images says whether some model makes pictures; nil when the
// pictures page is not mounted.
images func() bool
meshes func() bool
guardLibrary func() guard.Config
// licenceChoices and licencePrefs offer the choice of licences on the
// profile page; nil offers none.
licenceChoices func() LicenceChoices
licencePrefs LicencePrefs
images func() bool
meshes func() bool
guardLibrary func() guard.Config
// guardFor names the guardrail policies in force for someone, and
// whether they keep nothing; nil when there are none.
guardFor func(guard.Subject) (string, bool)
@@ -193,6 +197,7 @@ func (p *AccountPages) Register(mux *http.ServeMux) {
mux.HandleFunc("POST /profile/keys", p.selfAudited(p.createKey))
mux.HandleFunc("POST /profile/keys/{id}/revoke", p.selfAudited(p.revokeKey))
mux.HandleFunc("POST /profile/password", p.selfAudited(p.changePassword))
mux.HandleFunc("POST /profile/licences", p.selfAudited(p.setLicences))
mux.HandleFunc("POST /profile/connect", p.selfAudited(p.connect))
mux.HandleFunc("GET /setup/{tool}", p.setupScript)
}
@@ -379,6 +384,11 @@ type profileData struct {
Models []string
Error string
// Licences is the choice of licences not to use; nil when not offered.
Licences *LicenceChoices
LicencesSaved bool
LicenceError string
PasswordChanged bool
PasswordError string
MinPassword int
@@ -505,6 +515,7 @@ func (p *AccountPages) render(w http.ResponseWriter, r *http.Request,
}
d.Keys = keys
p.fillPlaces(r.Context(), langOf(r), user, &d)
p.fillLicences(r.Context(), user.ID, &d)
render(w, r, "profile", d)
}
+142
View File
@@ -0,0 +1,142 @@
package web
import (
"context"
"net/http"
"regexp"
"slices"
"strings"
)
// LicenceChoice is one licence the catalog's models are under, as the
// profile page offers it.
type LicenceChoice struct {
// Key is what is stored when it is ticked: the licence's id, else its
// name, lowercased; "unspecified" for models whose entry names none.
Key string
Name, URL string
// Commercial is "yes" or "no" as the licence says, empty when it does
// not say.
Commercial string
ExcludedRegions []string
Models []string
// Excluded is whether the person has left it out.
Excluded bool
}
// LicenceChoices is the licences on offer, and what the rules can be about.
type LicenceChoices struct {
Licences []LicenceChoice
// Regions are those some licence in the catalog grants nothing in.
Regions []string
// AnyNonCommercial is whether some licence forbids commercial use.
AnyNonCommercial bool
// What the person has chosen, for the rules.
NonCommercial bool
ExcludedRegions []string
}
// LicencePrefs keeps what a person has said not to use.
type LicencePrefs interface {
UserExcludedLicences(ctx context.Context, userID string) ([]string, error)
SetUserExcludedLicences(ctx context.Context, userID string, licences []string) error
}
// Rule words, matched by the router.
const (
licenceRuleNonCommercial = "rule:non-commercial"
licenceRuleRegion = "rule:region:"
)
var regionCode = regexp.MustCompile(`^[A-Z]{2}$`)
// SetLicences offers the choice of licences on the profile page: what the
// catalog's models are under, and where the choices are kept.
func (p *AccountPages) SetLicences(choices func() LicenceChoices, prefs LicencePrefs) {
p.licenceChoices, p.licencePrefs = choices, prefs
}
// fillLicences puts the choice, and what the person has made of it, on the
// profile page; nothing when it is not offered.
func (p *AccountPages) fillLicences(ctx context.Context, userID string, d *profileData) {
if p.licenceChoices == nil || p.licencePrefs == nil {
return
}
c := p.licenceChoices()
ex, err := p.licencePrefs.UserExcludedLicences(ctx, userID)
if err != nil {
p.log.Error("could not read a person's licence choices", "err", err)
}
for i := range c.Licences {
c.Licences[i].Excluded = slices.ContainsFunc(ex, func(e string) bool { return strings.EqualFold(e, c.Licences[i].Key) })
}
for _, e := range ex {
switch {
case e == licenceRuleNonCommercial:
c.NonCommercial = true
case strings.HasPrefix(e, licenceRuleRegion):
c.ExcludedRegions = append(c.ExcludedRegions, strings.TrimPrefix(e, licenceRuleRegion))
}
}
// A region the person excluded that no licence in the catalog names yet
// is still offered, ticked: it is there for the model added next.
for _, reg := range c.ExcludedRegions {
if !slices.Contains(c.Regions, reg) {
c.Regions = append(c.Regions, reg)
}
}
slices.Sort(c.Regions)
d.Licences = &c
}
func (p *AccountPages) setLicences(w http.ResponseWriter, r *http.Request) {
noStore(w)
sess, user, ok := p.session(r)
if !ok {
http.Redirect(w, r, "/login", http.StatusSeeOther)
return
}
if p.licencePrefs == nil {
http.NotFound(w, r)
return
}
if !p.accounts.CheckCSRF(sess, r.FormValue("csrf")) {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if err := r.ParseForm(); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
var ex []string
for _, k := range r.Form["licence"] {
if k = strings.TrimSpace(k); k != "" && !strings.HasPrefix(k, "rule:") {
ex = append(ex, strings.ToLower(k))
}
}
if r.FormValue("non_commercial") != "" {
ex = append(ex, licenceRuleNonCommercial)
}
regions := r.Form["region"]
regions = append(regions, strings.FieldsFunc(r.FormValue("regions_other"), func(c rune) bool {
return c == ',' || c == ' '
})...)
l := langOf(r)
for _, reg := range regions {
reg = strings.ToUpper(strings.TrimSpace(reg))
if reg == "" {
continue
}
if !regionCode.MatchString(reg) {
p.render(w, r, sess, user, profileData{LicenceError: l.T("profile.licences.err_region", reg)})
return
}
ex = append(ex, licenceRuleRegion+reg)
}
if err := p.licencePrefs.SetUserExcludedLicences(r.Context(), user.ID, ex); err != nil {
p.log.Error("could not keep a person's licence choices", "err", err)
p.render(w, r, sess, user, profileData{LicenceError: l.T("profile.err.try_again")})
return
}
p.render(w, r, sess, user, profileData{LicencesSaved: true})
}
+84
View File
@@ -0,0 +1,84 @@
package web
import (
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"slices"
"strings"
"testing"
"time"
"gitea.mynodes.xyz/ilker/llmgw/internal/store"
)
func TestTheProfileKeepsTheLicencesAPersonLeavesOut(t *testing.T) {
ctx := t.Context()
st, err := store.OpenSQLite(ctx, filepath.Join(t.TempDir(), "l.db"))
if err != nil {
t.Fatal(err)
}
defer st.Close()
ada := store.User{ID: "usr-a", Email: "ada@example.com", State: store.UserActive, CreatedAt: time.Now()}
if err := st.CreateUser(ctx, ada); err != nil {
t.Fatal(err)
}
p := NewAccountPages(fakeAccounts{user: ada}, st, nil, "v0", slog.New(slog.DiscardHandler))
p.SetLicences(func() LicenceChoices {
return LicenceChoices{
Licences: []LicenceChoice{
{Key: "mit", Name: "MIT", Commercial: "yes", Models: []string{"triposr"}},
{Key: "tencent-hunyuan-community", Name: "Tencent Hunyuan Community",
ExcludedRegions: []string{"EU", "UK", "KR"}, Models: []string{"hunyuan3d"}},
},
Regions: []string{"EU", "KR", "UK"},
}
}, st)
mux := http.NewServeMux()
p.Register(mux)
do := func(method string, form url.Values) string {
var req *http.Request
if form == nil {
req = httptest.NewRequest(method, "/profile", nil)
} else {
form.Set("csrf", "tok")
req = httptest.NewRequest(method, "/profile/licences", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
req.AddCookie(&http.Cookie{Name: SessionCookie, Value: "good"})
req.AddCookie(&http.Cookie{Name: csrfCookie, Value: "tok"})
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
return rec.Body.String()
}
page := do(http.MethodGet, nil)
for _, want := range []string{`action="/profile/licences"`, "Tencent Hunyuan Community", "not in EU, UK, KR", "hunyuan3d"} {
if !strings.Contains(page, want) {
t.Errorf("the page lacks %q", want)
}
}
saved := do(http.MethodPost, url.Values{"region": {"EU"}, "regions_other": {"ch, NO"}, "licence": {"MIT"},
"non_commercial": {"1"}})
got, _ := st.UserExcludedLicences(ctx, ada.ID)
want := []string{"mit", "rule:non-commercial", "rule:region:CH", "rule:region:EU", "rule:region:NO"}
if !slices.Equal(got, want) || !strings.Contains(saved, "Saved.") {
t.Errorf("kept %v, want %v", got, want)
}
// What was kept is what the page shows ticked, a region no licence
// names yet included.
if !strings.Contains(saved, `value="CH" checked`) || !strings.Contains(saved, `value="mit" checked`) {
t.Error("the page does not show what was kept")
}
bad := do(http.MethodPost, url.Values{"regions_other": {"Europe"}})
if !strings.Contains(bad, "is not a region code") {
t.Error("a bad region was not refused")
}
if got2, _ := st.UserExcludedLicences(ctx, ada.ID); !slices.Equal(got2, want) {
t.Errorf("a refused form changed what was kept: %v", got2)
}
}
+16
View File
@@ -143,6 +143,22 @@
"profile.new_password": "New password",
"profile.change_password": "Change password",
"profile.password_note": "Changing it signs out every other browser, which is the point if\nyou are changing it because something went wrong.",
"profile.licences": "Licences",
"profile.licences.intro": "Models under a licence you leave out here are not listed to you and do not answer your keys or this portal — for example, nothing made under a licence that excludes where your product is sold.",
"profile.licences.rules": "Leave out every licence that",
"profile.licences.non_commercial": "forbids commercial use",
"profile.licences.region": "grants nothing in %s",
"profile.licences.regions_other": "Also regions not listed (ISO codes, EU for the union)",
"profile.licences.regions_example": "EU, UK",
"profile.licences.each": "Or these licences",
"profile.licences.unspecified": "No licence stated",
"profile.licences.commercial_yes": "commercial use allowed",
"profile.licences.commercial_no": "non-commercial",
"profile.licences.not_in": "not in %s",
"profile.licences.save": "Save",
"profile.licences.saved": "Saved. Your keys follow it within a minute.",
"profile.licences.err_region": "%q is not a region code: two capital letters, or EU",
"profile.licences.note": "The rules also cover models added later. A licence that says nothing about commercial use or regions is not caught by them; tick it here if you have not checked it.",
"profile.err.personal_off": "personal keys are off on this gateway; choose a project",
"profile.err.try_again": "something went wrong; try again",
"profile.err.not_member": "you are not a member of that project",
+16
View File
@@ -143,6 +143,22 @@
"profile.new_password": "Yeni parola",
"profile.change_password": "Parolayı değiştir",
"profile.password_note": "Parolayı değiştirmek diğer tüm tarayıcılardaki oturumları kapatır; bir sorun\nolduğu için değiştiriyorsanız amaç da zaten budur.",
"profile.licences": "Lisanslar",
"profile.licences.intro": "Burada dışarıda bıraktığınız lisanslardaki modeller size listelenmez, anahtarlarınıza ve bu portala yanıt vermez — örneğin ürününüzün satıldığı bölgeyi dışlayan bir lisansla üretilmiş hiçbir şey.",
"profile.licences.rules": "Şu lisansların hepsini dışarıda bırak",
"profile.licences.non_commercial": "ticari kullanıma izin vermeyenler",
"profile.licences.region": "%s bölgesinde hak tanımayanlar",
"profile.licences.regions_other": "Listede olmayan bölgeler de (ISO kodları, birlik için EU)",
"profile.licences.regions_example": "EU, UK",
"profile.licences.each": "Ya da şu lisanslar",
"profile.licences.unspecified": "Lisansı belirtilmemiş",
"profile.licences.commercial_yes": "ticari kullanım serbest",
"profile.licences.commercial_no": "ticari değil",
"profile.licences.not_in": "%s dışında",
"profile.licences.save": "Kaydet",
"profile.licences.saved": "Kaydedildi. Anahtarlarınız bir dakika içinde buna uyar.",
"profile.licences.err_region": "%q bir bölge kodu değil: iki büyük harf ya da EU",
"profile.licences.note": "Kurallar sonradan eklenen modelleri de kapsar. Ticari kullanım ya da bölge hakkında bir şey söylemeyen lisanslar kurallara takılmaz; kontrol etmediyseniz onları burada işaretleyin.",
"profile.err.personal_off": "bu ağ geçidinde kişisel anahtarlar kapalı; bir proje seçin",
"profile.err.try_again": "bir sorun oluştu; yeniden deneyin",
"profile.err.not_member": "o projenin üyesi değilsiniz",
+24
View File
@@ -200,6 +200,30 @@ document.addEventListener("click", (e) => {
{{else}}<p class="empty">{{t "selfuse.nowhere"}}</p>{{end}}
<p class="note">{{t "selfuse.strictest"}}</p>
{{with .Licences}}
<h2 id="licences">{{t "profile.licences"}}</h2>
{{if $.LicencesSaved}}<p>{{t "profile.licences.saved"}}</p>{{end}}
{{if $.LicenceError}}<p class="error">{{$.LicenceError}}</p>{{end}}
<p class="note">{{t "profile.licences.intro"}}</p>
<form method="post" action="/profile/licences" class="narrow">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<fieldset><legend>{{t "profile.licences.rules"}}</legend>
<label class="check"><input type="checkbox" name="non_commercial" value="1"{{if .NonCommercial}} checked{{end}}>
{{t "profile.licences.non_commercial"}}</label>
{{range .Regions}}<label class="check"><input type="checkbox" name="region" value="{{.}}"{{if has $.Licences.ExcludedRegions .}} checked{{end}}>
{{t "profile.licences.region" .}}</label>{{end}}
<label>{{t "profile.licences.regions_other"}}<input type="text" name="regions_other" placeholder="{{t "profile.licences.regions_example"}}" autocomplete="off"></label>
</fieldset>
<fieldset><legend>{{t "profile.licences.each"}}</legend>
{{range .Licences}}<label class="check"><input type="checkbox" name="licence" value="{{.Key}}"{{if .Excluded}} checked{{end}}>
{{if .Name}}{{if .URL}}<a href="{{.URL}}" rel="noopener noreferrer">{{.Name}}</a>{{else}}{{.Name}}{{end}}{{else}}{{t "profile.licences.unspecified"}}{{end}}
<span class="opt">{{if eq .Commercial "yes"}}{{t "profile.licences.commercial_yes"}} · {{else if eq .Commercial "no"}}{{t "profile.licences.commercial_no"}} · {{end}}{{with .ExcludedRegions}}{{t "profile.licences.not_in" (join .)}} · {{end}}{{join .Models}}</span></label>{{end}}
</fieldset>
<button type="submit">{{t "profile.licences.save"}}</button>
</form>
<p class="note">{{t "profile.licences.note"}}</p>
{{end}}
<h2>{{t "profile.password"}}</h2>
{{if .PasswordChanged}}<p>{{t "profile.password_changed"}}</p>{{end}}
{{if .PasswordError}}<p class="error">{{.PasswordError}}</p>{{end}}