feat: publish the Sandwich Hime source preview
Signed-off-by: Cole Speelman <gamertan@noreply.localhost>
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
SPDX-FileCopyrightText: 2025-2026 Cole Speelman
|
||||
SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
Original work in the Sandwich Hime sando runtime is Copyright (c) 2025-2026
|
||||
Cole Speelman except where a file or contribution identifies a different
|
||||
copyright holder. The project requires no copyright assignment; ownership of
|
||||
a contribution remains determined by applicable law and existing agreements.
|
||||
|
||||
This file is an ownership record, not an Apache NOTICE file and not an
|
||||
additional license term. The runtime is licensed under the Apache License,
|
||||
Version 2.0, in LICENSE.
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,19 @@
|
||||
<!-- SPDX-License-Identifier: Apache-2.0 -->
|
||||
|
||||
# sando runtime
|
||||
|
||||
`gamertan.com/sandwich-hime/sando` is the independent Apache-2.0 runtime ABI for Go generated by Sandwich Hime. It contains no compiler, router, HTTP server, middleware, reflection registry, project discovery, or development supervisor.
|
||||
|
||||
The stable surface is:
|
||||
|
||||
```go
|
||||
type Component interface {
|
||||
Render(context.Context, io.Writer) error
|
||||
}
|
||||
|
||||
type ComponentFunc func(context.Context, io.Writer) error
|
||||
```
|
||||
|
||||
`Render` invokes components; generated code uses the context-specific writer helpers and checks `ABI`. Opaque `TrustedHTML`, `TrustedURL`, `TrustedJS`, and `TrustedCSS` values can be constructed only by conspicuous `Trust*` calls in trusted application code.
|
||||
|
||||
The runtime has its own `go.mod`, Apache-2.0 license, `COPYRIGHT` record, semantic version, and `sando/vX.Y.Z` tags. It never imports the AGPL compiler. Importing the runtime does not make an application AGPL under the project's terms. Applications may license their own code and generated files under terms they choose to the extent they hold the necessary rights, while redistribution of the runtime remains subject to Apache-2.0.
|
||||
@@ -0,0 +1,87 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package sando is the small production runtime for code generated by Hime-san.
|
||||
// It contains rendering contracts and context-specific output helpers, but no
|
||||
// router, HTTP server, middleware, or development tooling.
|
||||
package sando
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
// ABI identifies the generated-code contract implemented by this version of
|
||||
// the runtime. Generated files should reference this constant so that their
|
||||
// expected ABI is visible to readers and tooling.
|
||||
const ABI = "sando.v1"
|
||||
|
||||
// RuntimeABI is a descriptive alias for ABI.
|
||||
const RuntimeABI = ABI
|
||||
|
||||
var (
|
||||
// ErrNilComponent is returned when Render is asked to render a nil
|
||||
// component, including a typed nil held in a Component interface.
|
||||
ErrNilComponent = errors.New("sando: nil component")
|
||||
// ErrNilContext is returned when a component is rendered with a nil
|
||||
// context.Context.
|
||||
ErrNilContext = errors.New("sando: nil context")
|
||||
// ErrNilWriter is returned when a component is rendered with a nil writer.
|
||||
ErrNilWriter = errors.New("sando: nil writer")
|
||||
)
|
||||
|
||||
// Component is the complete production rendering contract. Components are
|
||||
// values rather than HTTP handlers so applications retain ownership of
|
||||
// buffering, routing, headers, status codes, and error policy.
|
||||
type Component interface {
|
||||
Render(context.Context, io.Writer) error
|
||||
}
|
||||
|
||||
// ComponentFunc adapts a function to Component.
|
||||
type ComponentFunc func(context.Context, io.Writer) error
|
||||
|
||||
// Render calls f with ctx and w.
|
||||
func (f ComponentFunc) Render(ctx context.Context, w io.Writer) error {
|
||||
if f == nil {
|
||||
return ErrNilComponent
|
||||
}
|
||||
if ctx == nil {
|
||||
return ErrNilContext
|
||||
}
|
||||
if isNil(w) {
|
||||
return ErrNilWriter
|
||||
}
|
||||
return f(ctx, w)
|
||||
}
|
||||
|
||||
// Render renders component into w. It reports nil inputs as errors rather than
|
||||
// panicking, including typed nil component and writer values.
|
||||
func Render(ctx context.Context, w io.Writer, component Component) error {
|
||||
if ctx == nil {
|
||||
return ErrNilContext
|
||||
}
|
||||
if isNil(w) {
|
||||
return ErrNilWriter
|
||||
}
|
||||
if isNil(component) {
|
||||
return ErrNilComponent
|
||||
}
|
||||
return component.Render(ctx, w)
|
||||
}
|
||||
|
||||
// isNil recognizes typed nil values stored in interfaces. It is intentionally
|
||||
// confined to API boundary validation and is not a component registry.
|
||||
func isNil(value any) bool {
|
||||
if value == nil {
|
||||
return true
|
||||
}
|
||||
|
||||
rv := reflect.ValueOf(value)
|
||||
switch rv.Kind() {
|
||||
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
|
||||
return rv.IsNil()
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package sando_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"gamertan.com/sandwich-hime/sando"
|
||||
)
|
||||
|
||||
func TestRender(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
component := sando.ComponentFunc(func(ctx context.Context, w io.Writer) error {
|
||||
_, err := io.WriteString(w, ctx.Value(contextKey{}).(string))
|
||||
return err
|
||||
})
|
||||
ctx := context.WithValue(context.Background(), contextKey{}, "rendered")
|
||||
var output bytes.Buffer
|
||||
|
||||
if err := sando.Render(ctx, &output, component); err != nil {
|
||||
t.Fatalf("Render() error = %v", err)
|
||||
}
|
||||
if got, want := output.String(), "rendered"; got != want {
|
||||
t.Fatalf("Render() output = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderPropagatesComponentError(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
want := errors.New("render failed")
|
||||
component := sando.ComponentFunc(func(context.Context, io.Writer) error { return want })
|
||||
if got := sando.Render(context.Background(), io.Discard, component); !errors.Is(got, want) {
|
||||
t.Fatalf("Render() error = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderRejectsNilInputs(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
valid := sando.ComponentFunc(func(context.Context, io.Writer) error { return nil })
|
||||
var nilFunc sando.ComponentFunc
|
||||
var nilPointer *pointerComponent
|
||||
var nilWriter *bytes.Buffer
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
ctx context.Context
|
||||
writer io.Writer
|
||||
component sando.Component
|
||||
want error
|
||||
}{
|
||||
{name: "nil context", writer: io.Discard, component: valid, want: sando.ErrNilContext},
|
||||
{name: "nil writer", ctx: context.Background(), component: valid, want: sando.ErrNilWriter},
|
||||
{name: "typed nil writer", ctx: context.Background(), writer: nilWriter, component: valid, want: sando.ErrNilWriter},
|
||||
{name: "nil component", ctx: context.Background(), writer: io.Discard, want: sando.ErrNilComponent},
|
||||
{name: "nil component func", ctx: context.Background(), writer: io.Discard, component: nilFunc, want: sando.ErrNilComponent},
|
||||
{name: "typed nil component", ctx: context.Background(), writer: io.Discard, component: nilPointer, want: sando.ErrNilComponent},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
test := test
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
if got := sando.Render(test.ctx, test.writer, test.component); !errors.Is(got, test.want) {
|
||||
t.Fatalf("Render() error = %v, want %v", got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestComponentFuncDirectValidation(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var nilFunc sando.ComponentFunc
|
||||
if got := nilFunc.Render(context.Background(), io.Discard); !errors.Is(got, sando.ErrNilComponent) {
|
||||
t.Fatalf("nil ComponentFunc.Render() error = %v", got)
|
||||
}
|
||||
|
||||
valid := sando.ComponentFunc(func(context.Context, io.Writer) error { return nil })
|
||||
if got := valid.Render(nil, io.Discard); !errors.Is(got, sando.ErrNilContext) {
|
||||
t.Fatalf("ComponentFunc.Render(nil, writer) error = %v", got)
|
||||
}
|
||||
if got := valid.Render(context.Background(), nil); !errors.Is(got, sando.ErrNilWriter) {
|
||||
t.Fatalf("ComponentFunc.Render(ctx, nil) error = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
type contextKey struct{}
|
||||
|
||||
type pointerComponent struct{}
|
||||
|
||||
func (*pointerComponent) Render(context.Context, io.Writer) error { return nil }
|
||||
@@ -0,0 +1,5 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
module gamertan.com/sandwich-hime/sando
|
||||
|
||||
go 1.25
|
||||
@@ -0,0 +1,40 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package sando
|
||||
|
||||
// TrustedHTML is HTML whose author has deliberately accepted responsibility
|
||||
// for its safety. Its contents are opaque outside this package.
|
||||
type TrustedHTML struct{ value string }
|
||||
|
||||
// TrustHTML marks value as deliberately trusted HTML. The caller is responsible
|
||||
// for supplying a balanced fragment that is valid at an HTML content boundary
|
||||
// and does not leave the parser in a different context. Prefer ordinary values
|
||||
// and WriteText whenever possible.
|
||||
func TrustHTML(value string) TrustedHTML { return TrustedHTML{value: value} }
|
||||
|
||||
// TrustedURL is a URL whose author has deliberately accepted responsibility
|
||||
// for its scheme and navigation behavior. HTML attribute syntax is still
|
||||
// escaped when the value is written.
|
||||
type TrustedURL struct{ value string }
|
||||
|
||||
// TrustURL marks value as a deliberately trusted URL, bypassing the ordinary
|
||||
// URL scheme allowlist. It does not bypass HTML attribute escaping.
|
||||
func TrustURL(value string) TrustedURL { return TrustedURL{value: value} }
|
||||
|
||||
// TrustedJS is JavaScript whose author has deliberately accepted
|
||||
// responsibility for its safety. Its contents are opaque outside this package.
|
||||
type TrustedJS struct{ value string }
|
||||
|
||||
// TrustJS marks value as deliberately trusted JavaScript. The caller is also
|
||||
// responsible for preventing an HTML </script sequence from terminating its
|
||||
// container. Plain strings cannot be passed to WriteJS.
|
||||
func TrustJS(value string) TrustedJS { return TrustedJS{value: value} }
|
||||
|
||||
// TrustedCSS is CSS whose author has deliberately accepted responsibility for
|
||||
// its safety. Its contents are opaque outside this package.
|
||||
type TrustedCSS struct{ value string }
|
||||
|
||||
// TrustCSS marks value as deliberately trusted CSS. The caller is also
|
||||
// responsible for preventing an HTML </style sequence from terminating its
|
||||
// container. Plain strings cannot be passed to WriteCSS.
|
||||
func TrustCSS(value string) TrustedCSS { return TrustedCSS{value: value} }
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package sando
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"html"
|
||||
"io"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// ErrUnsafeURL is the sentinel wrapped by URLSafetyError when an ordinary URL
|
||||
// value is ambiguous or uses a scheme outside the v1 allowlist.
|
||||
var ErrUnsafeURL = errors.New("sando: unsafe URL")
|
||||
|
||||
// URLSafetyError reports why an ordinary URL was rejected. It intentionally
|
||||
// does not retain or print the complete value, which may contain sensitive
|
||||
// application data.
|
||||
type URLSafetyError struct {
|
||||
Scheme string
|
||||
Reason string
|
||||
}
|
||||
|
||||
// Error implements error.
|
||||
func (e *URLSafetyError) Error() string {
|
||||
if e.Scheme != "" {
|
||||
return fmt.Sprintf("%v: scheme %q is not allowed", ErrUnsafeURL, e.Scheme)
|
||||
}
|
||||
if e.Reason != "" {
|
||||
return fmt.Sprintf("%v: %s", ErrUnsafeURL, e.Reason)
|
||||
}
|
||||
return ErrUnsafeURL.Error()
|
||||
}
|
||||
|
||||
// Unwrap permits errors.Is(err, ErrUnsafeURL).
|
||||
func (e *URLSafetyError) Unwrap() error { return ErrUnsafeURL }
|
||||
|
||||
// WriteString writes a compiler-owned static literal and reports both writer
|
||||
// errors and contract-violating short writes. Application data must use the
|
||||
// context-specific helpers below instead.
|
||||
func WriteString(w io.Writer, value string) error {
|
||||
return writeString(w, value)
|
||||
}
|
||||
|
||||
// WriteText writes value escaped for an HTML text node.
|
||||
func WriteText(w io.Writer, value any) error {
|
||||
if trusted, ok := value.(TrustedHTML); ok {
|
||||
return writeString(w, trusted.value)
|
||||
}
|
||||
return writeString(w, html.EscapeString(normalizeText(stringValue(value))))
|
||||
}
|
||||
|
||||
// WriteRCDATA writes value escaped for an HTML RCDATA element such as title
|
||||
// or textarea. Trusted wrappers are intentionally not honored in this context:
|
||||
// their contents are escaped like every other value so they cannot close the
|
||||
// containing element.
|
||||
func WriteRCDATA(w io.Writer, value any) error {
|
||||
return writeString(w, html.EscapeString(normalizeText(stringValue(value))))
|
||||
}
|
||||
|
||||
// WriteAttr writes value escaped for a quoted HTML attribute. Generated code
|
||||
// must always place this output inside a syntactically complete quoted value.
|
||||
func WriteAttr(w io.Writer, value any) error {
|
||||
return writeString(w, html.EscapeString(normalizeText(stringValue(value))))
|
||||
}
|
||||
|
||||
// WriteURL writes value escaped for a quoted URL-bearing HTML attribute.
|
||||
// Ordinary values are canonicalized and checked before any bytes are written.
|
||||
// TrustedURL bypasses the scheme check but never attribute escaping.
|
||||
func WriteURL(w io.Writer, value any) error {
|
||||
if trusted, ok := value.(TrustedURL); ok {
|
||||
return writeString(w, html.EscapeString(normalizeText(trusted.value)))
|
||||
}
|
||||
|
||||
canonical, err := canonicalURL(stringValue(value))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return writeString(w, html.EscapeString(canonical))
|
||||
}
|
||||
|
||||
// WriteHTML writes deliberately trusted HTML without escaping.
|
||||
func WriteHTML(w io.Writer, value TrustedHTML) error {
|
||||
return writeString(w, value.value)
|
||||
}
|
||||
|
||||
// WriteJS writes deliberately trusted JavaScript without escaping.
|
||||
func WriteJS(w io.Writer, value TrustedJS) error {
|
||||
return writeString(w, value.value)
|
||||
}
|
||||
|
||||
// WriteCSS writes deliberately trusted CSS without escaping.
|
||||
func WriteCSS(w io.Writer, value TrustedCSS) error {
|
||||
return writeString(w, value.value)
|
||||
}
|
||||
|
||||
func writeString(w io.Writer, value string) error {
|
||||
if isNil(w) {
|
||||
return ErrNilWriter
|
||||
}
|
||||
|
||||
n, err := io.WriteString(w, value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n != len(value) {
|
||||
return io.ErrShortWrite
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func stringValue(value any) string {
|
||||
switch value := value.(type) {
|
||||
case TrustedHTML:
|
||||
return value.value
|
||||
case TrustedURL:
|
||||
return value.value
|
||||
case TrustedJS:
|
||||
return value.value
|
||||
case TrustedCSS:
|
||||
return value.value
|
||||
default:
|
||||
return fmt.Sprint(value)
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeText(value string) string {
|
||||
if !utf8.ValidString(value) {
|
||||
value = strings.ToValidUTF8(value, "\uFFFD")
|
||||
}
|
||||
return strings.ReplaceAll(value, "\x00", "\uFFFD")
|
||||
}
|
||||
|
||||
func canonicalURL(value string) (string, error) {
|
||||
value = normalizeText(value)
|
||||
value = strings.TrimFunc(value, func(r rune) bool {
|
||||
return unicode.IsSpace(r) || r == '\uFEFF'
|
||||
})
|
||||
|
||||
for _, r := range value {
|
||||
if r < 0x20 || r == 0x7f {
|
||||
return "", &URLSafetyError{Reason: "control characters are not allowed"}
|
||||
}
|
||||
}
|
||||
|
||||
colon := strings.IndexByte(value, ':')
|
||||
boundary := strings.IndexAny(value, "/?#")
|
||||
if colon < 0 || boundary >= 0 && boundary < colon {
|
||||
return value, nil
|
||||
}
|
||||
|
||||
scheme := value[:colon]
|
||||
if !validScheme(scheme) {
|
||||
return "", &URLSafetyError{Reason: "ambiguous scheme syntax"}
|
||||
}
|
||||
|
||||
scheme = strings.ToLower(scheme)
|
||||
switch scheme {
|
||||
case "http", "https", "mailto", "tel":
|
||||
return value, nil
|
||||
default:
|
||||
return "", &URLSafetyError{Scheme: scheme}
|
||||
}
|
||||
}
|
||||
|
||||
func validScheme(value string) bool {
|
||||
if value == "" || !isASCIIAlpha(value[0]) {
|
||||
return false
|
||||
}
|
||||
for i := 1; i < len(value); i++ {
|
||||
c := value[i]
|
||||
if !isASCIIAlpha(c) && (c < '0' || c > '9') && c != '+' && c != '-' && c != '.' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func isASCIIAlpha(c byte) bool {
|
||||
return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z'
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package sando_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
|
||||
"gamertan.com/sandwich-hime/sando"
|
||||
)
|
||||
|
||||
func TestWriteText(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
value any
|
||||
want string
|
||||
}{
|
||||
{name: "quote and entity injection", value: `<script x="'&">alert(1)</script>`, want: `<script x="'&">alert(1)</script>`},
|
||||
{name: "unicode preserved", value: "姫 🍞 café", want: "姫 🍞 café"},
|
||||
{name: "NUL replaced", value: "left\x00right", want: "left\uFFFDright"},
|
||||
{name: "invalid UTF-8 replaced", value: string([]byte{'a', 0xff, 'b'}), want: "a\uFFFDb"},
|
||||
{name: "non-string formatted", value: 42, want: "42"},
|
||||
{name: "trusted HTML is deliberately raw in text context", value: sando.TrustHTML("<b>explicitly trusted</b>"), want: "<b>explicitly trusted</b>"},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
test := test
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
var output bytes.Buffer
|
||||
if err := sando.WriteText(&output, test.value); err != nil {
|
||||
t.Fatalf("WriteText() error = %v", err)
|
||||
}
|
||||
if got := output.String(); got != test.want {
|
||||
t.Fatalf("WriteText() = %q, want %q", got, test.want)
|
||||
}
|
||||
if !utf8.ValidString(output.String()) {
|
||||
t.Fatal("WriteText() emitted invalid UTF-8")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteAttr(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
value any
|
||||
want string
|
||||
}{
|
||||
{name: "breakout characters", value: `x" autofocus onfocus="alert(1)&`, want: `x" autofocus onfocus="alert(1)&`},
|
||||
{name: "angle and apostrophe", value: `<'value'>`, want: `<'value'>`},
|
||||
{name: "unicode and NUL", value: "姫\x00さん", want: "姫\uFFFDさん"},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
test := test
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
var output bytes.Buffer
|
||||
if err := sando.WriteAttr(&output, test.value); err != nil {
|
||||
t.Fatalf("WriteAttr() error = %v", err)
|
||||
}
|
||||
if got := output.String(); got != test.want {
|
||||
t.Fatalf("WriteAttr() = %q, want %q", got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteRCDATAAlwaysEscapesTrustedValues(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
value any
|
||||
want string
|
||||
}{
|
||||
{name: "plain", value: `</title><script>alert("x")</script>`, want: `</title><script>alert("x")</script>`},
|
||||
{name: "trusted HTML", value: sando.TrustHTML(`</textarea><script>alert(1)</script>`), want: `</textarea><script>alert(1)</script>`},
|
||||
{name: "trusted URL", value: sando.TrustURL(`javascript:</title>`), want: `javascript:</title>`},
|
||||
{name: "trusted JavaScript", value: sando.TrustJS(`</title><script>alert(1)</script>`), want: `</title><script>alert(1)</script>`},
|
||||
{name: "trusted CSS", value: sando.TrustCSS(`</textarea><style>*{display:none}</style>`), want: `</textarea><style>*{display:none}</style>`},
|
||||
{name: "unicode and NUL", value: "姫\x00さん", want: "姫\uFFFDさん"},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
test := test
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
var output bytes.Buffer
|
||||
if err := sando.WriteRCDATA(&output, test.value); err != nil {
|
||||
t.Fatalf("WriteRCDATA() error = %v", err)
|
||||
}
|
||||
if got := output.String(); got != test.want {
|
||||
t.Fatalf("WriteRCDATA() = %q, want %q", got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteRCDATAAlwaysEscapesTrustedHTML(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var output bytes.Buffer
|
||||
value := sando.TrustHTML(`</textarea><script>alert(1)</script>`)
|
||||
if err := sando.WriteRCDATA(&output, value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, want := output.String(), `</textarea><script>alert(1)</script>`; got != want {
|
||||
t.Fatalf("WriteRCDATA() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteURLAllowsAndCanonicalizesOrdinaryValues(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
value any
|
||||
want string
|
||||
}{
|
||||
{name: "root relative", value: "/items?q=tea&sort=name", want: "/items?q=tea&sort=name"},
|
||||
{name: "path relative", value: "../images/姫.png", want: "../images/姫.png"},
|
||||
{name: "fragment", value: "#section", want: "#section"},
|
||||
{name: "network path", value: "//static.example/assets", want: "//static.example/assets"},
|
||||
{name: "HTTP scheme case insensitive", value: "HTTP://example.test/a", want: "HTTP://example.test/a"},
|
||||
{name: "HTTPS", value: "https://example.test/", want: "https://example.test/"},
|
||||
{name: "mail", value: "mailto:hime@example.test", want: "mailto:hime@example.test"},
|
||||
{name: "telephone", value: "tel:+14165550123", want: "tel:+14165550123"},
|
||||
{name: "surrounding whitespace trimmed", value: " \n\thttps://example.test/path\r ", want: "https://example.test/path"},
|
||||
{name: "colon after query is relative", value: "/search?q=kind:value", want: "/search?q=kind:value"},
|
||||
{name: "empty", value: "", want: ""},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
test := test
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
var output bytes.Buffer
|
||||
if err := sando.WriteURL(&output, test.value); err != nil {
|
||||
t.Fatalf("WriteURL() error = %v", err)
|
||||
}
|
||||
if got := output.String(); got != test.want {
|
||||
t.Fatalf("WriteURL() = %q, want %q", got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteURLRejectsDangerousAndAmbiguousValuesBeforeWriting(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
values := []string{
|
||||
"javascript:alert(1)",
|
||||
"JaVaScRiPt:alert(1)",
|
||||
"data:text/html,<script>alert(1)</script>",
|
||||
"vbscript:msgbox(1)",
|
||||
"file:///etc/passwd",
|
||||
"ftp://example.test/file",
|
||||
"java\nscript:alert(1)",
|
||||
"java\tscript:alert(1)",
|
||||
"java\x00script:alert(1)",
|
||||
"javascript\x7f:alert(1)",
|
||||
"java script:alert(1)",
|
||||
"%6aavascript:alert(1)",
|
||||
":ambiguous",
|
||||
}
|
||||
|
||||
for _, value := range values {
|
||||
value := value
|
||||
t.Run(value, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
var output bytes.Buffer
|
||||
output.WriteString("last-good")
|
||||
err := sando.WriteURL(&output, value)
|
||||
if !errors.Is(err, sando.ErrUnsafeURL) {
|
||||
t.Fatalf("WriteURL() error = %v, want ErrUnsafeURL", err)
|
||||
}
|
||||
if got := output.String(); got != "last-good" {
|
||||
t.Fatalf("WriteURL() modified writer on validation failure: %q", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrustedWrites(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
write func(io.Writer) error
|
||||
want string
|
||||
}{
|
||||
{name: "HTML", write: func(w io.Writer) error {
|
||||
return sando.WriteHTML(w, sando.TrustHTML(`<strong data-x="1">Hime</strong>`))
|
||||
}, want: `<strong data-x="1">Hime</strong>`},
|
||||
{name: "URL bypasses scheme but not attribute escaping", write: func(w io.Writer) error { return sando.WriteURL(w, sando.TrustURL(`custom:"<&`)) }, want: `custom:"<&`},
|
||||
{name: "JavaScript", write: func(w io.Writer) error { return sando.WriteJS(w, sando.TrustJS(`window.hime = "<3";`)) }, want: `window.hime = "<3";`},
|
||||
{name: "CSS", write: func(w io.Writer) error { return sando.WriteCSS(w, sando.TrustCSS(`.hime::after { content: "<3"; }`)) }, want: `.hime::after { content: "<3"; }`},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
test := test
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
var output bytes.Buffer
|
||||
if err := test.write(&output); err != nil {
|
||||
t.Fatalf("trusted write error = %v", err)
|
||||
}
|
||||
if got := output.String(); got != test.want {
|
||||
t.Fatalf("trusted write = %q, want %q", got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteHelpersPropagateWriterFailures(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
want := errors.New("disk full")
|
||||
tests := []struct {
|
||||
name string
|
||||
write func(io.Writer) error
|
||||
}{
|
||||
{name: "static literal", write: func(w io.Writer) error { return sando.WriteString(w, "hello") }},
|
||||
{name: "text", write: func(w io.Writer) error { return sando.WriteText(w, "hello") }},
|
||||
{name: "RCDATA", write: func(w io.Writer) error { return sando.WriteRCDATA(w, "hello") }},
|
||||
{name: "attribute", write: func(w io.Writer) error { return sando.WriteAttr(w, "hello") }},
|
||||
{name: "URL", write: func(w io.Writer) error { return sando.WriteURL(w, "/hello") }},
|
||||
{name: "HTML", write: func(w io.Writer) error { return sando.WriteHTML(w, sando.TrustHTML("hello")) }},
|
||||
{name: "JavaScript", write: func(w io.Writer) error { return sando.WriteJS(w, sando.TrustJS("hello")) }},
|
||||
{name: "CSS", write: func(w io.Writer) error { return sando.WriteCSS(w, sando.TrustCSS("hello")) }},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
test := test
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
if got := test.write(errorWriter{err: want}); !errors.Is(got, want) {
|
||||
t.Fatalf("write error = %v, want %v", got, want)
|
||||
}
|
||||
if got := test.write(shortWriter{}); !errors.Is(got, io.ErrShortWrite) {
|
||||
t.Fatalf("short write error = %v, want io.ErrShortWrite", got)
|
||||
}
|
||||
if got := test.write(nil); !errors.Is(got, sando.ErrNilWriter) {
|
||||
t.Fatalf("nil writer error = %v, want ErrNilWriter", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestURLSafetyErrorDoesNotEchoSensitiveValue(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const secret = "user:password@example.test"
|
||||
err := sando.WriteURL(io.Discard, "custom:"+secret)
|
||||
if err == nil {
|
||||
t.Fatal("WriteURL() unexpectedly accepted custom scheme")
|
||||
}
|
||||
if strings.Contains(err.Error(), secret) {
|
||||
t.Fatalf("error leaks URL contents: %q", err)
|
||||
}
|
||||
var safetyError *sando.URLSafetyError
|
||||
if !errors.As(err, &safetyError) {
|
||||
t.Fatalf("error type = %T, want *sando.URLSafetyError", err)
|
||||
}
|
||||
}
|
||||
|
||||
type errorWriter struct{ err error }
|
||||
|
||||
func (w errorWriter) Write([]byte) (int, error) { return 0, w.err }
|
||||
|
||||
type shortWriter struct{}
|
||||
|
||||
func (shortWriter) Write(value []byte) (int, error) {
|
||||
if len(value) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
return len(value) - 1, nil
|
||||
}
|
||||
Reference in New Issue
Block a user