Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions server/api/cards.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ func (a *API) registerCardsRoutes(r *mux.Router) {
r.HandleFunc("/boards/{boardID}/cards", a.sessionRequired(a.handleGetCards)).Methods("GET")
r.HandleFunc("/cards/{cardID}", a.sessionRequired(a.handlePatchCard)).Methods("PATCH")
r.HandleFunc("/cards/{cardID}", a.sessionRequired(a.handleGetCard)).Methods("GET")
r.HandleFunc("/teams/{teamID}/cards/by-ticket-code/{ticketCode}", a.sessionRequired(a.handleGetCardByTicketCode)).Methods("GET")
}

func (a *API) handleCreateCard(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -390,3 +391,74 @@ func (a *API) handleGetCard(w http.ResponseWriter, r *http.Request) {

auditRec.Success()
}

func (a *API) handleGetCardByTicketCode(w http.ResponseWriter, r *http.Request) {
// swagger:operation GET /teams/{teamID}/cards/by-ticket-code/{ticketCode} getCardByTicketCode
//
// Fetches a card by its ticket code (e.g. PROJ-42).
//
// ---
// produces:
// - application/json
// parameters:
// - name: teamID
// in: path
// description: Team ID
// required: true
// type: string
// - name: ticketCode
// in: path
// description: Ticket code (e.g. PROJ-42)
// required: true
// type: string
// security:
// - BearerAuth: []
// responses:
// '200':
// description: success
// schema:
// $ref: '#/definitions/Card'
// default:
// description: internal error
// schema:
// "$ref": "#/definitions/ErrorResponse"

userID := getUserID(r)
teamID := mux.Vars(r)["teamID"]
ticketCode := mux.Vars(r)["ticketCode"]

card, err := a.app.GetCardByTicketCode(ticketCode, teamID)
if err != nil {
a.errorResponse(w, r, err)
return
}

if !a.permissions.HasPermissionToBoard(userID, card.BoardID, model.PermissionViewBoard) {
a.errorResponse(w, r, model.NewErrPermission("access denied to fetch card"))
return
Comment on lines +430 to +438
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Mask unauthorized ticket-code hits as not found.

This lookup happens before the board permission check, and the handler returns a different result for “exists but forbidden” vs “doesn’t exist”. Because ticket codes are predictable, that lets callers enumerate cards on private boards. Prefer folding access control into the query or returning a 404-equivalent when PermissionViewBoard fails.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/api/cards.go` around lines 430 - 438, The handler currently calls
a.app.GetCardByTicketCode(ticketCode, teamID) then checks
a.permissions.HasPermissionToBoard(userID, card.BoardID,
model.PermissionViewBoard), which leaks existence; either (A) fold permission
into the lookup by adding/using a.app.GetCardByTicketCodeWithAccess(ticketCode,
teamID, userID) (or extend GetCardByTicketCode to accept userID) so the DB query
enforces board view permission and returns not-found when unauthorized, or (B)
if changing the app layer is undesirable, change the post-lookup branch to mask
forbidden access by calling a.errorResponse(w, r, model.NewErrNotFound("card not
found")) (or the handler’s 404-equivalent) instead of returning a permission
error when a.permissions.HasPermissionToBoard(...) is false; update calls to
a.errorResponse and tests accordingly.

}

auditRec := a.makeAuditRecord(r, "getCardByTicketCode", audit.Fail)
defer a.audit.LogRecord(audit.LevelRead, auditRec)
auditRec.AddMeta("teamID", teamID)
auditRec.AddMeta("ticketCode", ticketCode)
auditRec.AddMeta("cardID", card.ID)

a.logger.Debug("GetCardByTicketCode",
mlog.String("teamID", teamID),
mlog.String("ticketCode", ticketCode),
mlog.String("cardID", card.ID),
mlog.String("userID", userID),
)

data, err := json.Marshal(card)
if err != nil {
a.errorResponse(w, r, err)
return
}

// response
jsonBytesResponse(w, http.StatusOK, data)

auditRec.Success()
}
52 changes: 52 additions & 0 deletions server/app/cards.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,19 @@ func (a *App) CreateCard(card *model.Card, boardID string, userID string, disabl
card.UpdateAt = now
card.DeleteAt = 0

// Auto-assign ticket number: atomically increment the board's card counter
cardNumber, err := a.store.IncrementBoardCardCount(boardID)
if err != nil {
return nil, fmt.Errorf("cannot assign ticket number: %w", err)
}
card.CardNumber = cardNumber

// Generate the ticket code if the board has a prefix
board, err := a.store.GetBoard(boardID)
if err == nil && board.CardPrefix != "" {
card.TicketCode = fmt.Sprintf("%s-%d", board.CardPrefix, cardNumber)
}

block := model.Card2Block(card)

newBlocks, err := a.InsertBlocksAndNotify([]*model.Block{block}, userID, disableNotify)
Expand All @@ -34,6 +47,11 @@ func (a *App) CreateCard(card *model.Card, boardID string, userID string, disabl
return nil, err
}

// Re-attach the ticket code (it's not stored in block fields, it's computed)
if board != nil && board.CardPrefix != "" {
newCard.TicketCode = fmt.Sprintf("%s-%d", board.CardPrefix, newCard.CardNumber)
}

return newCard, nil
}

Expand All @@ -50,12 +68,18 @@ func (a *App) GetCardsForBoard(boardID string, page int, perPage int) ([]*model.
return nil, err
}

// Fetch board prefix for ticket code computation
board, _ := a.store.GetBoard(boardID)

cards := make([]*model.Card, 0, len(blocks))
for _, blk := range blocks {
b := blk
if card, err := model.Block2Card(b); err != nil {
return nil, fmt.Errorf("Block2Card fail: %w", err)
} else {
if board != nil && board.CardPrefix != "" && card.CardNumber > 0 {
card.TicketCode = fmt.Sprintf("%s-%d", board.CardPrefix, card.CardNumber)
}
cards = append(cards, card)
}
}
Expand Down Expand Up @@ -92,5 +116,33 @@ func (a *App) GetCardByID(cardID string) (*model.Card, error) {
return nil, err
}

// Populate ticket code from board prefix
if card.CardNumber > 0 {
board, boardErr := a.store.GetBoard(card.BoardID)
if boardErr == nil && board.CardPrefix != "" {
card.TicketCode = fmt.Sprintf("%s-%d", board.CardPrefix, card.CardNumber)
}
}

return card, nil
}

func (a *App) GetCardByTicketCode(ticketCode string, teamID string) (*model.Card, error) {
prefix, number, err := model.ParseTicketCode(ticketCode)
if err != nil {
return nil, err
}

block, err := a.store.GetCardByTicketCode(prefix, number, teamID)
if err != nil {
return nil, err
}

card, err := model.Block2Card(block)
if err != nil {
return nil, err
}

card.TicketCode = ticketCode
return card, nil
}
23 changes: 23 additions & 0 deletions server/model/board.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ const (
BoardSearchFieldNone BoardSearchField = ""
BoardSearchFieldTitle BoardSearchField = "title"
BoardSearchFieldPropertyName BoardSearchField = "property_name"
BoardSearchFieldCardPrefix BoardSearchField = "card_prefix"
)

// Board groups a set of blocks and its layout
Expand Down Expand Up @@ -97,6 +98,14 @@ type Board struct {
// required: false
CardProperties []map[string]interface{} `json:"cardProperties"`

// The short prefix used for ticket codes (e.g. "PROJ", "BUG")
// required: false
CardPrefix string `json:"cardPrefix"`

// The auto-incrementing counter for card ticket numbers
// required: false
CardCount int64 `json:"cardCount"`

// The creation time in miliseconds since the current epoch
// required: true
CreateAt int64 `json:"createAt"`
Expand Down Expand Up @@ -156,6 +165,10 @@ type BoardPatch struct {
// required: false
ChannelID *string `json:"channelId"`

// The short prefix used for ticket codes (e.g. "PROJ", "BUG")
// required: false
CardPrefix *string `json:"cardPrefix"`

// The board updated properties
// required: false
UpdatedProperties map[string]interface{} `json:"updatedProperties"`
Expand Down Expand Up @@ -297,6 +310,10 @@ func (p *BoardPatch) Patch(board *Board) *Board {
board.ChannelID = *p.ChannelID
}

if p.CardPrefix != nil {
board.CardPrefix = *p.CardPrefix
}
Comment on lines +313 to +315
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Harden cardPrefix validation on the server.

This only checks length and then persists the raw value unchanged. API callers can still save lowercase, whitespace, or hyphenated prefixes, which makes the new lookup path unreliable because ParseTicketCode() uppercases the prefix and splits on -. Please enforce the same uppercase-alphanumeric max-10 contract here when the value is non-empty, and reuse that check from Board.IsValid() so create/import paths are covered too.

Also applies to: 397-399

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/model/board.go` around lines 313 - 315, When assigning p.CardPrefix to
board.CardPrefix (and the other occurrence at the same pattern later), trim and
uppercase the incoming string and validate it with the same
uppercase-alphanumeric ≤10 rule used by Board.IsValid() (or extract that prefix
check into a shared helper and call it here). Specifically: if p.CardPrefix !=
nil, let v = strings.TrimSpace(*p.CardPrefix); if v != "" set v =
strings.ToUpper(v) and run the Board.IsValid()/shared IsValidCardPrefix helper
to ensure only uppercase A-Z0-9 and max length 10; if validation fails return
the appropriate error instead of persisting the raw value, otherwise set
board.CardPrefix = v. Also apply the identical change at the other assignment
block referenced (lines ~397-399).


for key, property := range p.UpdatedProperties {
board.Properties[key] = property
}
Expand Down Expand Up @@ -377,6 +394,10 @@ func (p *BoardPatch) IsValid() error {
return InvalidBoardErr{"invalid-channel-id"}
}

if p.CardPrefix != nil && len(*p.CardPrefix) > 10 {
return InvalidBoardErr{"invalid-card-prefix-too-long"}
}

return nil
}

Expand Down Expand Up @@ -447,6 +468,8 @@ func BoardSearchFieldFromString(field string) (BoardSearchField, error) {
return BoardSearchFieldTitle, nil
case string(BoardSearchFieldPropertyName):
return BoardSearchFieldPropertyName, nil
case string(BoardSearchFieldCardPrefix):
return BoardSearchFieldCardPrefix, nil
}
return BoardSearchFieldNone, ErrInvalidBoardSearchField
}
48 changes: 48 additions & 0 deletions server/model/card.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,38 @@
package model

import (
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"

"github.com/mattermost/mattermost-plugin-boards/server/utils"
"github.com/rivo/uniseg"
)

var ErrBoardIDMismatch = errors.New("Board IDs do not match")
var ErrInvalidTicketCode = errors.New("invalid ticket code format, expected PREFIX-NUMBER")

// ParseTicketCode parses a ticket code like "PROJ-42" into its prefix ("PROJ") and number (42).
func ParseTicketCode(ticketCode string) (string, int64, error) {
parts := strings.SplitN(ticketCode, "-", 2)
if len(parts) != 2 {
return "", 0, ErrInvalidTicketCode
}

prefix := strings.TrimSpace(parts[0])
if prefix == "" {
return "", 0, ErrInvalidTicketCode
}

number, err := strconv.ParseInt(strings.TrimSpace(parts[1]), 10, 64)
if err != nil || number <= 0 {
return "", 0, ErrInvalidTicketCode
}

return strings.ToUpper(prefix), number, nil
}

type ErrInvalidCard struct {
msg string
Expand Down Expand Up @@ -76,6 +100,14 @@ type Card struct {
// required: false
Properties map[string]any `json:"properties"`

// The sequential card number within the board (auto-assigned)
// required: false
CardNumber int64 `json:"cardNumber"`

// The full ticket code combining board prefix and card number (e.g. "PROJ-42")
// required: false
TicketCode string `json:"ticketCode,omitempty"`

// The creation time in milliseconds since the current epoch
// required: false
CreateAt int64 `json:"createAt"`
Expand Down Expand Up @@ -203,6 +235,7 @@ func Card2Block(card *Card) *Block {
fields["icon"] = card.Icon
fields["isTemplate"] = card.IsTemplate
fields["properties"] = card.Properties
fields["cardNumber"] = card.CardNumber

return &Block{
ID: card.ID,
Expand Down Expand Up @@ -230,6 +263,7 @@ func Block2Card(block *Block) (*Card, error) {
icon := ""
isTemplate := false
properties := make(map[string]any)
var cardNumber int64

if co, ok := block.Fields["contentOrder"]; ok {
switch arr := co.(type) {
Expand Down Expand Up @@ -274,6 +308,19 @@ func Block2Card(block *Block) (*Card, error) {
}
}

if cn, ok := block.Fields["cardNumber"]; ok {
switch v := cn.(type) {
case float64:
cardNumber = int64(v)
case int64:
cardNumber = v
case json.Number:
if n, err := v.Int64(); err == nil {
cardNumber = n
}
}
}

card := &Card{
ID: block.ID,
BoardID: block.BoardID,
Expand All @@ -284,6 +331,7 @@ func Block2Card(block *Block) (*Card, error) {
Icon: icon,
IsTemplate: isTemplate,
Properties: properties,
CardNumber: cardNumber,
CreateAt: block.CreateAt,
UpdateAt: block.UpdateAt,
DeleteAt: block.DeleteAt,
Expand Down
30 changes: 30 additions & 0 deletions server/services/store/mockstore/mockstore.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading