Files
nexarch/dms/internal/cmis/handler.go
patrickandClaude Sonnet 5 237c1bd9fb
CI / Core-Modul (Build/Vet/Test) (push) Canceled after 0s
CI / DMS Security-Test-Gate (AC5, Merge-Gate) (push) Canceled after 0s
CI / DMS-Modul (Lint/Build/Test/Coverage/Artefakt) (push) Canceled after 0s
CI / DMS-Modul Supply-Chain-Scan (govulncheck) (push) Canceled after 0s
CI / Web (dms-browser) (push) Canceled after 0s
CI / Web (pdf-viewer) (push) Canceled after 0s
CI / Web (shl) (push) Canceled after 0s
INT-15: identitaetspruefung fuer CMIS in den gemeinsamen Guard, Paritaetstests
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 00:19:52 +02:00

377 lines
11 KiB
Go

package cmis
import (
"encoding/json"
"errors"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
)
const browserPath = "/cmis/browser"
type Config struct {
RepositoryID string
Name string
Version string
RESTPrefix string
Backend http.Handler
PublicBaseURL string
MaxContentBytes int64
}
type handler struct {
cfg Config
rest rest
}
// Mount haengt die CMIS-Routen in api; ohne Aufruf existiert keine CMIS-Route.
func Mount(api *http.ServeMux, cfg Config) error {
if cfg.RepositoryID == "" || cfg.Backend == nil {
return errors.New("cmis: repository-id und backend sind pflicht")
}
if cfg.Name == "" {
cfg.Name = "NEXARCH DMS"
}
if cfg.MaxContentBytes <= 0 {
cfg.MaxContentBytes = 256 << 20
}
h := &handler{cfg: cfg, rest: rest{backend: cfg.Backend, prefix: cfg.RESTPrefix}}
api.HandleFunc("GET "+browserPath, h.get)
api.HandleFunc("GET "+browserPath+"/{repo}", h.get)
api.HandleFunc("GET "+browserPath+"/{repo}/{path...}", h.get)
api.HandleFunc("POST "+browserPath+"/{repo}", h.post)
api.HandleFunc("POST "+browserPath+"/{repo}/{path...}", h.post)
return nil
}
type cmisError struct {
status int
exception string
message string
}
func (e *cmisError) write(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(e.status)
_ = json.NewEncoder(w).Encode(map[string]any{
"exception": e.exception,
"message": e.message,
"error": map[string]string{"code": codeFor(e.status), "message": e.message},
})
}
func codeFor(status int) string {
switch status {
case http.StatusBadRequest:
return "invalid_request"
case http.StatusUnauthorized:
return "unauthenticated"
case http.StatusForbidden:
return "forbidden"
case http.StatusNotFound:
return "not_found"
case http.StatusMethodNotAllowed:
return "method_not_allowed"
case http.StatusConflict:
return "conflict"
case http.StatusServiceUnavailable:
return "unavailable"
}
return "internal_error"
}
func errorFromResult(res result) *cmisError {
msg := ""
var b struct {
Error struct {
Message string `json:"message"`
} `json:"error"`
}
if json.Unmarshal(res.body, &b) == nil {
msg = b.Error.Message
}
if msg == "" {
msg = http.StatusText(res.code)
}
switch res.code {
case http.StatusBadRequest, http.StatusRequestEntityTooLarge, http.StatusUnsupportedMediaType, http.StatusUnprocessableEntity:
return &cmisError{http.StatusBadRequest, "invalidArgument", msg}
case http.StatusUnauthorized:
return &cmisError{http.StatusUnauthorized, "unauthorized", msg}
case http.StatusForbidden:
return &cmisError{http.StatusForbidden, "permissionDenied", msg}
case http.StatusNotFound:
return &cmisError{http.StatusNotFound, "objectNotFound", msg}
case http.StatusConflict, http.StatusLocked:
return &cmisError{http.StatusConflict, "constraint", msg}
case http.StatusServiceUnavailable:
return &cmisError{http.StatusServiceUnavailable, "runtime", msg}
}
return &cmisError{http.StatusInternalServerError, "runtime", msg}
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
func notSupported(what string) *cmisError {
return &cmisError{http.StatusMethodNotAllowed, "notSupported", what + " wird von dieser CMIS-Schnittstelle nicht unterstuetzt"}
}
func invalid(msg string) *cmisError { return &cmisError{http.StatusBadRequest, "invalidArgument", msg} }
func notFound(msg string) *cmisError { return &cmisError{http.StatusNotFound, "objectNotFound", msg} }
func (h *handler) baseURL(r *http.Request) string {
if h.cfg.PublicBaseURL != "" {
return strings.TrimRight(h.cfg.PublicBaseURL, "/")
}
scheme := "http"
if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {
scheme = "https"
}
host := r.Header.Get("X-Forwarded-Host")
if host == "" {
host = r.Host
}
return scheme + "://" + host + h.cfg.RESTPrefix
}
func (h *handler) repositoryInfo(r *http.Request) map[string]any {
repoURL := h.baseURL(r) + browserPath + "/" + h.cfg.RepositoryID
return map[string]any{
"repositoryId": h.cfg.RepositoryID, "repositoryName": h.cfg.Name,
"repositoryDescription": "Dokumentenmanagement (NEXARCH), CMIS-Zugriff auf Ordner und Dokumente",
"vendorName": "NEXARCH", "productName": "NEXARCH DMS", "productVersion": h.cfg.Version,
"rootFolderId": rootID, "cmisVersionSupported": "1.1", "thinClientURI": "",
"principalIdAnonymous": "anonymous", "principalIdAnyone": "anyone",
"repositoryUrl": repoURL, "rootFolderUrl": repoURL + "/root",
"changesIncomplete": false, "changesOnType": []string{},
"capabilities": map[string]any{
"capabilityContentStreamUpdatability": "none", "capabilityChanges": "none", "capabilityRenditions": "none",
"capabilityGetDescendants": false, "capabilityGetFolderTree": false, "capabilityMultifiling": false,
"capabilityUnfiling": false, "capabilityVersionSpecificFiling": false, "capabilityPWCUpdatable": false,
"capabilityPWCSearchable": false, "capabilityAllVersionsSearchable": false, "capabilityQuery": "none",
"capabilityJoin": "none", "capabilityAcl": "none",
},
}
}
func (h *handler) get(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
repo := r.PathValue("repo")
if repo == "" {
writeJSON(w, http.StatusOK, map[string]any{h.cfg.RepositoryID: h.repositoryInfo(r)})
return
}
if repo != h.cfg.RepositoryID {
notFound("unbekanntes repository").write(w)
return
}
succinct := q.Get("succinct") == "true"
selector := q.Get("cmisselector")
pathParam := r.PathValue("path")
var cerr *cmisError
switch selector {
case "", "repositoryInfo", "object", "children", "parent", "content":
if selector == "" {
selector = "repositoryInfo"
if pathParam != "" || q.Get("objectId") != "" {
selector = "object"
}
}
if selector == "repositoryInfo" {
writeJSON(w, http.StatusOK, map[string]any{h.cfg.RepositoryID: h.repositoryInfo(r)})
return
}
cerr = h.objectSelector(w, r, selector, pathParam, succinct)
case "typeDefinition":
if def, ok := typeDefinition(q.Get("typeId")); ok {
writeJSON(w, http.StatusOK, def)
} else {
cerr = notFound("unbekannter typ")
}
case "typeChildren":
var types []any
if q.Get("typeId") == "" {
for _, id := range []string{typeDocument, typeFolder} {
def, _ := typeDefinition(id)
types = append(types, def)
}
}
writeJSON(w, http.StatusOK, map[string]any{"types": types, "hasMoreItems": false, "numItems": len(types)})
case "typeDescendants":
var list []any
for _, id := range []string{typeDocument, typeFolder} {
def, _ := typeDefinition(id)
list = append(list, map[string]any{"type": def, "children": []any{}})
}
writeJSON(w, http.StatusOK, list)
default:
cerr = notSupported("selector " + selector)
}
if cerr != nil {
cerr.write(w)
}
}
func (h *handler) objectSelector(w http.ResponseWriter, r *http.Request, selector, pathParam string, succinct bool) *cmisError {
q := r.URL.Query()
var obj object
var cerr *cmisError
if pathParam != "" {
obj, cerr = h.byPath(r, pathParam)
} else {
id := q.Get("objectId")
if id == "" {
id = rootID
}
obj, cerr = h.byID(r, id)
}
if cerr != nil {
return cerr
}
switch selector {
case "object":
writeJSON(w, http.StatusOK, obj.json(succinct))
case "children":
if !obj.folder {
return invalid("nur ordner haben kinder")
}
return h.children(w, r, obj, succinct)
case "parent":
if !obj.folder || obj.id == rootID {
return notFound("kein uebergeordneter ordner")
}
parent, cerr := h.byID(r, *obj.parentID)
if cerr != nil {
return cerr
}
writeJSON(w, http.StatusOK, parent.json(succinct))
case "content":
if obj.folder {
return &cmisError{http.StatusConflict, "constraint", "ordner haben keinen inhalt"}
}
if q.Get("download") == "attachment" {
w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+url.PathEscape(obj.name))
}
return h.rest.stream(w, r, "/documents/"+obj.id+"/content")
}
return nil
}
func (h *handler) byID(r *http.Request, id string) (object, *cmisError) {
if !validID(id) {
return object{}, notFound("objekt nicht gefunden")
}
if id == rootID {
return rootObject(), nil
}
var f folderDTO
cerr := h.rest.getJSON(r, "/folders/"+id, nil, &f)
if cerr == nil {
return f.object(), nil
}
if cerr.status != http.StatusNotFound {
return object{}, cerr
}
var d documentDTO
if cerr := h.rest.getJSON(r, "/documents/"+id, nil, &d); cerr != nil {
return object{}, cerr
}
return d.object(), nil
}
func (h *handler) childLists(r *http.Request, folderID string) ([]folderDTO, []documentDTO, *cmisError) {
foldersPath, docsPath := "/folders/children", "/folders/documents"
if folderID != rootID {
foldersPath, docsPath = "/folders/"+folderID+"/children", "/folders/"+folderID+"/documents"
}
var folders []folderDTO
if cerr := h.rest.getJSON(r, foldersPath, nil, &folders); cerr != nil {
return nil, nil, cerr
}
var docs []documentDTO
if cerr := h.rest.getJSON(r, docsPath, nil, &docs); cerr != nil {
return nil, nil, cerr
}
return folders, docs, nil
}
func (h *handler) byPath(r *http.Request, path string) (object, *cmisError) {
segs := strings.Split(strings.Trim(path, "/"), "/")
if segs[0] != rootID {
return object{}, notFound("pfad muss unterhalb von root liegen")
}
cur := rootObject()
for i, seg := range segs[1:] {
if seg == "" || !cur.folder {
return object{}, notFound("pfad nicht gefunden")
}
folders, docs, cerr := h.childLists(r, cur.id)
if cerr != nil {
return object{}, cerr
}
found := false
for _, f := range folders {
if f.Name == seg {
cur, found = f.object(), true
cur.path = "/" + strings.Join(segs[1:i+2], "/")
break
}
}
if !found && i == len(segs)-2 {
for _, d := range docs {
if d.Title == seg {
cur, found = d.object(), true
break
}
}
}
if !found {
return object{}, notFound("pfad nicht gefunden")
}
}
return cur, nil
}
func (h *handler) children(w http.ResponseWriter, r *http.Request, parent object, succinct bool) *cmisError {
folders, docs, cerr := h.childLists(r, parent.id)
if cerr != nil {
return cerr
}
sort.SliceStable(folders, func(i, j int) bool { return folders[i].Name < folders[j].Name })
var all []object
for _, f := range folders {
o := f.object()
o.path = strings.TrimRight(parent.path, "/") + "/" + f.Name
all = append(all, o)
}
for _, d := range docs {
all = append(all, d.object())
}
total := len(all)
skip, _ := strconv.Atoi(r.URL.Query().Get("skipCount"))
if skip < 0 || skip > total {
skip = total
}
end := total
if mx, err := strconv.Atoi(r.URL.Query().Get("maxItems")); err == nil && mx >= 0 && skip+mx < total {
end = skip + mx
}
items := make([]any, 0, end-skip)
for _, o := range all[skip:end] {
items = append(items, map[string]any{"object": o.json(succinct)})
}
writeJSON(w, http.StatusOK, map[string]any{"objects": items, "hasMoreItems": end < total, "numItems": total})
return nil
}