feat: v0 — glpi-go client, mglpi CLI, mglpi-mcp, fake-GLPI test suite [#767]

https://projects.knownelement.com/issues/767#note-4191
This commit is contained in:
2026-09-04 08:41:25 -05:00
commit 5da1eee08f
26 changed files with 4956 additions and 0 deletions
+6
View File
@@ -0,0 +1,6 @@
# Credentials NEVER live in the repo. Any *.env landing here is ignored
# as a tripwire (env.example is the only committed shape).
*.env
bin/
.smoke/
.crush/
+661
View File
@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+19
View File
@@ -0,0 +1,19 @@
# Makefile: thin front door over dev.sh so `make build/vet/test/check/smoke`
# route through the digest-pinned Docker builder (ALL dev work in Docker —
# the host never runs a Go toolchain).
.PHONY: build vet test check smoke
build:
@./dev.sh build
vet:
@./dev.sh vet
test:
@./dev.sh test
check:
@./dev.sh check
smoke:
@./dev.sh smoke
+216
View File
@@ -0,0 +1,216 @@
# mopac-glpi-go
A 100% Go client library, CLI (`mglpi`), and MCP server (`mglpi-mcp`)
for the GLPI REST API (ITSM/CMDB). Replaces python glue for every CMDB
update: one static binary, zero third-party modules (stdlib only),
machine-parseable JSON output, and tokens that never appear in flags,
logs, or error strings. Clones the architecture of
[mopac-redmine-go](https://git.knownelement.com/ukrrs/mopac-redmine-go)
file for file.
Status: 2026-09-03 — v0 complete and green: changes (create / show /
list / transition / followup), CI search + raw item fetch, profiles +
agent-profile auto-switch, session lifecycle (init / kill), 0600
env-file config, `-o json` on every command, exit codes 0/1/2 with
one-line API-error stderr, and a stdio MCP server (initialize /
tools-list / 6 tools). Built and tested entirely against a fake GLPI
(unit suite + end-to-end smoke); the live CMDB
(cmdb.knownelement.com) attaches with zero code change via
`MGLPI_URL`/`MGLPI_APP_TOKEN`/`MGLPI_USER_TOKEN`. [#767]
## Architecture
```mermaid
flowchart LR
subgraph host[Host]
M[mglpi CLI\nbin/mglpi] --config 0600 env --> M
P[mglpi-mcp\nstdio JSON-RPC] --> M
S[smoke/smoke.sh]
end
subgraph docker[Digest-pinned Docker builder — ALL dev]
B[go build / vet / test]
F[smoke/fakeglpi\nstateful in-memory GLPI]
end
subgraph wire[Library: package glpi]
C[Client\nApp-Token + Session-Token headers only]
end
M --> C
P --> C
C --> F
C -.-> G[(real GLPI\ncmdb.knownelement.com)]
S --> B
S --> F
```
All compilation, vetting, and testing runs inside the digest-pinned
`golang:1.26-bookworm` builder (`./dev.sh`); the host never runs a Go
toolchain. Tests and smoke talk only to the in-process/containerized
fake; the real CMDB is never contacted by the test suite.
## GLPI quirks modeled (and tested)
- **Create endpoints return an ARRAY**: `[{"id":N,"message":"..."}]`
never an object. `CreateChange` / `AddFollowup` parse it.
- **Input shapes differ per endpoint**: Change create takes
`{"input":{...}}` (object); ITILFollowup REQUIRES
`{"input":[{...}]}` (array of objects) — the fake rejects the wrong
shape with a 400, and the client sends each faithfully.
- **Search rows are keyed by field-id string** under forcedisplay:
`{"data":[{"1":"name","2":7,"12":3}]}` — parsed into typed rows
(fields 1 name, 2 id, 12 status).
- **Sessions**: `POST /initSession` (App-Token + `Authorization:
user_token ...`) returns `{"session_token":"..."}`; every later call
carries `Session-Token`; `killSession` cleans up (the client re-inits
transparently afterwards).
- **Profiles**: `GET /getMyProfiles` lists the user's profiles;
`POST /changeActiveProfile` with `{"profiles_id":N}` switches the
session's active profile. Agent mode uses this to move into the right
role (e.g. 5 = Hotliner) before working.
- **initSession auth failures are auth failures**: GLPI answers 400
(ERROR_GLPI_LOGIN / ERROR_APP_TOKEN_...) for bad credentials — the
client maps that to `ErrAuth`, not `ErrValidation`.
## Quickstart (verified against the fake)
This is the exact flow the smoke run (`./dev.sh smoke`) executes:
```sh
./dev.sh check # build + vet + test inside the Docker builder
./dev.sh smoke # boots fake GLPI on 127.0.0.1:8602, drives bin/mglpi
# against the real CMDB instead (0600 env file, see env.example):
export MGLPI_URL=https://cmdb.knownelement.com/apirest.php
export MGLPI_APP_TOKEN=<app token>
export MGLPI_USER_TOKEN=<user token>
mglpi whoami # profiles, [active] marker
mglpi change create --title "Disk pressure" --urgency 4 <<'EOF'
- array05 on pfv-tsys5 at 92%
EOF
mglpi change list --status new
mglpi change show 104
mglpi change transition 104 solved
mglpi change followup 104 <<'EOF'
REPORT delivered: array expanded
EOF
mglpi ci search Computer web
mglpi ci show Computer 101 -o json
```
Agent mode: put `MGLPI_PROFILE_ID=5` in the env file (or pass
`--profile 5`) — the CLI switches to that profile right after
InitSession, so profile-gated servers accept the calls. `whoami` never
switches. Add `-o json` to any command for machine output.
## Command reference
| Command | Effect | Key flags |
|---|---|---|
| `whoami` | the session's GLPI profiles | `-o json` |
| `change create --title T` | create change (body from stdin) | `--content FILE\|-`, `--urgency 1..5`, `--impact 1..5`, `--profile N`, `-o json` |
| `change show ID` | one change with content | `-o json` |
| `change list` | search (forcedisplay 1/2/12) | `--status N\|NAME`, `-o json` |
| `change transition ID STATUS` | move status (name or number) | `-o json` (re-fetches) |
| `change followup ID` | append ITILFollowup (body from stdin) | `--content FILE\|-`, `--profile N` |
| `ci search TYPE TERM` | name-substring search | `-o json` |
| `ci show TYPE ID` | raw CI object | `-o json` (default shape) |
| `help` | usage | |
Flags may appear before or after positionals (`mglpi change show 104
-o json` parses).
## Configuration
| Source | Keys | Discipline |
|---|---|---|
| environment | `MGLPI_URL`, `MGLPI_APP_TOKEN`, `MGLPI_USER_TOKEN`, `MGLPI_PROFILE_ID` (optional) | env wins over file |
| `--config PATH` (also `$MGLPI_CONFIG`, default `~/.config/mglpi/env`) | same keys | file must be 0600 or stricter; refused before any read; parsed in pure Go (no sourcing/expansion) |
Tokens travel only in headers: `App-Token` on every request,
`Authorization: user_token ...` on initSession, `Session-Token` after.
Response bodies are never surfaced in error strings — the fake GLPI
deliberately echoes the presented token in error bodies, and the test
suite proves nothing leaks (`TestTokensNeverLeak`, plus the smoke
redaction pass).
## Exit codes and stderr
| Code | Meaning | stderr shape |
|---|---|---|
| 0 | ok | — |
| 1 | usage / config error | one line, names the problem (never values) |
| 2 | API error | one line: `mglpi: glpi: <sentinel>: http NNN` — parseable |
Sentinels (library): `glpi.ErrAuth`, `ErrNotFound`, `ErrValidation`,
`ErrServer`, `ErrUnreachable`, `ErrMalformedResponse` — all comparable
with `errors.Is`.
## Library surface (what the harness calls)
```go
import "git.knownelement.com/ukrrs/mopac-glpi-go/glpi"
c := glpi.New(glpi.Config{BaseURL: url, AppToken: app, UserToken: user})
_ = c.InitSession(ctx) // also lazy on first call
_ = c.ChangeActiveProfile(ctx, 5) // agent mode (5 = Hotliner)
profs, _ := c.GetMyProfiles(ctx) // id/name/is_active
id, _ := c.CreateChange(ctx, "title", "<p>content</p>", 3, 4)
ch, _ := c.GetChange(ctx, id) // full read shape
rows, _ := c.ListChanges(ctx, glpi.StatusNew) // search, fields 1/2/12
_ = c.TransitionChange(ctx, id, glpi.StatusSolved)
_ = c.AddFollowup(ctx, id, "note") // {"input":[{...}]} shape
cis, _ := c.SearchCI(ctx, "Computer", "web")
obj, _ := c.GetItem(ctx, "Computer", 101) // raw map for ci show
_ = c.KillSession(ctx)
```
Status helpers: `glpi.StatusNew`…`StatusClosed` constants,
`StatusName(id)`, `StatusID(name)`. All methods take a
`context.Context`.
## MCP server
`cmd/mglpi-mcp` is a minimal stdio JSON-RPC MCP server (stdlib only):
`initialize` (echoes protocol_version + serverInfo), `tools/list` (six
tools), `tools/call`, `ping`. Tool failures are results with
`isError: true`; only unknown methods are JSON-RPC errors (-32601).
```sh
docker exec -i mopac-cli-mglpi mglpi-mcp # from the compose exec-host
printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}' \
| mglpi-mcp --config ~/.creds/mglpi.env
```
Tools: `change_create`, `change_list`, `change_transition`,
`change_followup`, `ci_search`, `ci_show`.
## Development
```sh
./dev.sh build|vet|test|check|smoke|mglpi|mcp|shell # everything runs in the digest-pinned builder
make build|vet|test|check|smoke # same, Makefile front door
```
Test suite: table-driven round-trips against the stateful fake
(`internal/fakeglpi`): session/header discipline, create/array-reply
parsing, keyed search rows, transition, followup input-shape contract,
CI search, profiles + the RequireProfile rejection path (agent mode),
error mapping (400/401/403/404/422/5xx → sentinels),
unreachable/malformed handling, and token redaction. Shell scripts are
shellcheck-clean (including info level).
## Status
| Area | State |
|---|---|
| Library (changes, followups, search, profiles, sessions) | done, green |
| CLI surface (`mglpi`) | done, green |
| MCP server (`mglpi-mcp`, 6 tools) | done, green (handshake + calls tested) |
| Fake-GLPI test suite | done, green (unit + smoke) |
| Token redaction | done, tested (fake echoes all three tokens; nothing leaks) |
| Dev harness (Docker-only builds) | done (`dev.sh`/`Makefile`) |
| Live-CMDB verification | pending first live attach via `MGLPI_URL`/`MGLPI_APP_TOKEN`/`MGLPI_USER_TOKEN` |
License: AGPLv3 (see `LICENSE`). Pattern source:
https://git.knownelement.com/ukrrs/mopac-redmine-go
+47
View File
@@ -0,0 +1,47 @@
// Command mglpi-mcp is the GLPI MCP server (stdio JSON-RPC, stdlib
// only). Connection settings come from MGLPI_URL / MGLPI_APP_TOKEN /
// MGLPI_USER_TOKEN env vars (plus optional MGLPI_PROFILE_ID for agent
// mode) or a 0600 --config env file — the same discipline as mglpi.
package main
import (
"context"
"flag"
"fmt"
"os"
"git.knownelement.com/ukrrs/mopac-glpi-go/glpi"
"git.knownelement.com/ukrrs/mopac-glpi-go/internal/config"
"git.knownelement.com/ukrrs/mopac-glpi-go/internal/mcp"
)
func main() {
cfgPath := flag.String("config", "", "env file with MGLPI_URL/MGLPI_APP_TOKEN/MGLPI_USER_TOKEN (must be 0600)")
profile := flag.Int("profile", 0, "agent profile id to switch to after InitSession (overrides MGLPI_PROFILE_ID)")
flag.Parse()
if *cfgPath == "" {
*cfgPath = os.Getenv("MGLPI_CONFIG")
}
cfg, _, err := config.Load(*cfgPath)
if err != nil {
fmt.Fprintf(os.Stderr, "mglpi-mcp: %v\n", err)
os.Exit(1)
}
if *profile == 0 {
*profile = cfg.ProfileID
}
c := glpi.New(glpi.Config{
BaseURL: cfg.BaseURL,
AppToken: cfg.AppToken,
UserToken: cfg.UserToken,
})
if err := mcp.New(c, *profile).Serve(os.Stdin, os.Stdout); err != nil {
fmt.Fprintf(os.Stderr, "mglpi-mcp: %v\n", err)
os.Exit(1)
}
// Graceful close: release the session when the peer hangs up.
if err := c.KillSession(context.Background()); err != nil {
fmt.Fprintf(os.Stderr, "mglpi-mcp: killSession: %v\n", err)
}
}
+12
View File
@@ -0,0 +1,12 @@
// Command mglpi is the GLPI/CMDB CLI over the mopac-glpi-go library.
package main
import (
"os"
"git.knownelement.com/ukrrs/mopac-glpi-go/internal/cli"
)
func main() {
os.Exit(cli.Run(os.Args[1:], os.Stdout, os.Stderr))
}
+30
View File
@@ -0,0 +1,30 @@
# mglpi — the GLPI/CMDB CLI as a container (MOPAC fleet pattern).
#
# Built via `docker compose build mglpi` (glpi-go/docker-compose.yml),
# which tags mopac-mglpi:<ver>. Invocation is the TSYSGroupAIOS
# container-CLI pattern (no host binaries, no bin/ shortcuts):
#
# docker run --rm --env-file ~/.creds/mglpi.env mopac-mglpi:1 \
# change list --status new
# docker run --rm -i --env-file ~/.creds/mglpi.env mopac-mglpi:1 \
# mglpi-mcp # the stdio MCP surface (mglpi-mcp is argv[0])
#
# Both stages digest-pinned; the builder matches dev.sh (root AGENTS.md:
# ALL Go work through the golang:1.26-bookworm builder). The binaries are
# static (CGO off), so the runtime is bare alpine.
FROM golang@sha256:e8c859f5632dcfde7b32d2012b4351728f6437930887c2f6a91ea242459e5514 AS build
# = golang:1.26-bookworm
WORKDIR /src
COPY go.mod ./
COPY cmd ./cmd
COPY internal ./internal
COPY glpi ./glpi
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/mglpi ./cmd/mglpi \
&& CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/mglpi-mcp ./cmd/mglpi-mcp
FROM alpine@sha256:14358309a308569c32bdc37e2e0e9694be33a9d99e68afb0f5ff33cc1f695dce
# = alpine:3.22
COPY --from=build /out/mglpi /usr/local/bin/mglpi
COPY --from=build /out/mglpi-mcp /usr/local/bin/mglpi-mcp
ENTRYPOINT ["/usr/local/bin/mglpi"]
Executable
+82
View File
@@ -0,0 +1,82 @@
#!/bin/sh
# mopac-glpi-go dev wrapper. EVERY compile/vet/test path routes through
# the digest-pinned Docker builder (same image as mopac-redmine-go and
# mopac-keyproxy; the host runs containers, never toolchains).
#
# Usage: ./dev.sh {build|vet|test|check|smoke|mglpi|mcp|shell} [args...]
#
# build compile ./cmd/mglpi and ./cmd/mglpi-mcp into bin/
# vet go vet ./...
# test go test ./... (all tests run against the in-process fake
# GLPI server; the real CMDB is NEVER contacted)
# check build + vet + test (the pre-push gate)
# smoke end-to-end smoke: builds, boots the fake GLPI in a
# container on 127.0.0.1:8602, drives the real CLI from the
# host through 0600 env files (change create/list/show/
# transition/followup round-trips, ci search, agent-profile
# switch, -o json, MCP handshake, redaction check on stderr),
# tears everything down
# mglpi run the real CLI: rebuilds bin/mglpi (static) if any source
# is newer, then runs it inside the digest-pinned builder with
# MGLPI_URL/MGLPI_APP_TOKEN/MGLPI_USER_TOKEN/MGLPI_PROFILE_ID
# passed through from the caller's env (the harness loop
# exports them from loop.env; humans export their own).
# HARNESS_DOCKER_NETWORK (optional) joins the run to a named
# network (e2e fakes).
# mcp same as mglpi but runs the stdio MCP server (bin/mglpi-mcp)
# shell interactive sh inside the builder
set -e
IMAGE="golang@sha256:e8c859f5632dcfde7b32d2012b4351728f6437930887c2f6a91ea242459e5514" # = golang:1.26-bookworm (bash present; alpine lacks it)
run() {
docker run --rm -v "$PWD:/h" -w /h \
-u "$(id -u):$(id -g)" -e HOME=/tmp -e GOFLAGS=-buildvcs=false \
"$IMAGE" "$@"
}
cmd=${1:-check}
shift || true
case "$cmd" in
build)
run sh -c 'go build -o bin/mglpi ./cmd/mglpi && go build -o bin/mglpi-mcp ./cmd/mglpi-mcp'
;;
vet)
run go vet ./...
;;
test)
run go test "$@" ./...
;;
check)
run sh -c 'go build -o bin/mglpi ./cmd/mglpi && go build -o bin/mglpi-mcp ./cmd/mglpi-mcp && go vet ./... && go test ./...'
;;
smoke)
./smoke/smoke.sh
;;
mglpi|mcp)
# Rebuild-if-stale (static: the loop container is musl), then run the
# binary in the builder. Its own docker run: -e passthrough must come
# before the image, which run() cannot do.
bin=bin/mglpi
pkg=./cmd/mglpi
[ "$cmd" = "mcp" ] && bin=bin/mglpi-mcp && pkg=./cmd/mglpi-mcp
if [ ! -x "$bin" ] || [ -n "$(find cmd internal glpi glpi_test.go go.mod -newer "$bin" -print -quit 2>/dev/null)" ]; then
echo "dev.sh: $bin missing or stale -> static rebuild" >&2
run env CGO_ENABLED=0 go build -o "$bin" "$pkg"
fi
NET=""
if [ -n "$HARNESS_DOCKER_NETWORK" ]; then NET="--network $HARNESS_DOCKER_NETWORK"; fi
docker run --rm -i ${NET:+"$NET"} -v "$PWD:/h" -w /h \
-u "$(id -u):$(id -g)" -e HOME=/tmp \
-e MGLPI_URL -e MGLPI_APP_TOKEN -e MGLPI_USER_TOKEN -e MGLPI_PROFILE_ID \
"$IMAGE" "./$bin" "$@"
;;
shell)
run sh
;;
*)
echo "dev.sh: unknown command $cmd (build|vet|test|check|smoke|mglpi|mcp|shell)" >&2
exit 1
;;
esac
+38
View File
@@ -0,0 +1,38 @@
# glpi-go — the mglpi CLI exec-host. Image built here
# (`docker compose build mglpi`); the container runs PERSISTENTLY and
# every invocation is `docker exec` (Charles 2026-08-31):
#
# docker compose up -d mglpi # once, and at boot
# mglpi change list --status new # ~/.local/bin/mglpi shim:
# # docker exec -i mopac-cli-mglpi mglpi ...
# docker exec -i mopac-cli-mglpi mglpi-mcp # the MCP surface (stdio)
#
# DUAL-SURFACE RULE (Charles 2026-08-31): every connector repo carries
# BOTH its CLI and its MCP server (both binaries live in the same
# image; the MCP surface is exec'd with -i). ALWAYS scope compose ops to
# the exact service (`up -d mglpi`, `stop mglpi`, `rm -f mglpi`,
# `build mglpi`). NEVER bare `docker compose down` in a connector repo.
#
# Never `docker run` per invocation (ephemeral spins are where the cruft
# came from), never extracted binaries (outdated copies). The container
# is always the exact pinned image build.
#
# Live credentials: MGLPI_URL / MGLPI_APP_TOKEN / MGLPI_USER_TOKEN
# (plus optional MGLPI_PROFILE_ID) in a 0600 env file in ~/.creds
# (single place, Charles 2026-08-31; see env.example). Never committed,
# never logged.
name: mopac-glpi
services:
mglpi:
build:
context: .
dockerfile: deploy/Dockerfile.mglpi
image: mopac-mglpi:1
container_name: mopac-cli-mglpi
restart: unless-stopped
# Exec-host pattern: idle forever, serve `docker exec` sessions.
entrypoint: ["sleep", "infinity"]
env_file:
- ${MGLPI_CREDS:-/home/reachableceo/.creds}/mglpi.env
+9
View File
@@ -0,0 +1,9 @@
# mglpi connection env file (copy to ~/.creds/mglpi.env and chmod 600)
# MGLPI_URL, MGLPI_APP_TOKEN and MGLPI_USER_TOKEN are required;
# MGLPI_PROFILE_ID is optional (agent mode: auto-switch to this GLPI
# profile id, e.g. 5 = Hotliner, after InitSession). The file must be
# 0600 or stricter — mglpi refuses looser files before reading them.
MGLPI_URL=https://cmdb.knownelement.com/apirest.php
MGLPI_APP_TOKEN=your-glpi-app-token
MGLPI_USER_TOKEN=your-glpi-user-token
MGLPI_PROFILE_ID=0
+251
View File
@@ -0,0 +1,251 @@
package glpi
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
)
// Change status constants (GLPI change lifecycle).
const (
StatusNew = 1
StatusEvaluation = 2
StatusApproval = 3
StatusTest = 4
StatusQualification = 5
StatusWaiting = 6
StatusAccepted = 7
StatusAssigned = 8
StatusPlanned = 9
StatusPending = 10
StatusSolved = 11
StatusClosed = 12
)
// statusNames maps status ids to human names (CLI display + name-based
// transitions; GLPI has no enumeration endpoint for these).
var statusNames = map[int]string{
StatusNew: "new",
StatusEvaluation: "evaluation",
StatusApproval: "approval",
StatusTest: "test",
StatusQualification: "qualification",
StatusWaiting: "waiting",
StatusAccepted: "accepted",
StatusAssigned: "assigned",
StatusPlanned: "planned",
StatusPending: "pending",
StatusSolved: "solved",
StatusClosed: "closed",
}
// StatusName renders a status id ("new", "solved", ...) or "status N".
func StatusName(id int) string {
if n, ok := statusNames[id]; ok {
return n
}
return fmt.Sprintf("status %d", id)
}
// StatusID resolves a status name case-insensitively ("Solved" -> 11).
func StatusID(name string) (int, bool) {
for id, n := range statusNames {
if eqfold(n, name) {
return id, true
}
}
return 0, false
}
// Change is GLPI's read shape for one change (GET /change/<id>).
type Change struct {
ID int `json:"id"`
Name string `json:"name"`
Content string `json:"content"`
Status int `json:"status"`
Urgency int `json:"urgency"`
Impact int `json:"impact"`
Date string `json:"date"`
DateMod string `json:"date_mod"`
}
// ChangeRow is one row of a change search (fields 1 name, 2 id,
// 12 status).
type ChangeRow struct {
ID int `json:"id"`
Name string `json:"name"`
Status int `json:"status"`
}
// CreateChange creates a change (POST /change/) and returns its id.
//
// GLPI contract modeled faithfully: the payload is {"input":{...}} — an
// OBJECT (the ITILFollowup endpoint is the array-flavored one) — and
// the reply is an ARRAY: [{"id":N,"message":"..."}]. urgency and impact
// are GLPI's 1..5 scales (3 = medium).
func (c *Client) CreateChange(ctx context.Context, name, content string, urgency, impact int) (int, error) {
if name == "" {
return 0, fmt.Errorf("%w: change name required", ErrValidation)
}
if urgency < 1 || urgency > 5 || impact < 1 || impact > 5 {
return 0, fmt.Errorf("%w: urgency/impact must be 1..5", ErrValidation)
}
input := map[string]any{
"name": name,
"content": content,
}
if urgency != 0 {
input["urgency"] = urgency
}
if impact != 0 {
input["impact"] = impact
}
ids, err := c.postCreate(ctx, "/change", map[string]any{"input": input})
if err != nil {
return 0, err
}
if len(ids) == 0 || ids[0] == 0 {
return 0, fmt.Errorf("%w: create returned no id", ErrMalformedResponse)
}
return ids[0], nil
}
// postCreate sends a create payload and parses GLPI's ARRAY reply
// [{"id":N,"message":"..."}] into ids.
func (c *Client) postCreate(ctx context.Context, path string, payload any) ([]int, error) {
var arr []struct {
ID int `json:"id"`
Message string `json:"message"`
}
if err := c.call(ctx, http.MethodPost, path, nil, payload, &arr); err != nil {
return nil, err
}
ids := make([]int, 0, len(arr))
for _, a := range arr {
ids = append(ids, a.ID)
}
return ids, nil
}
// GetChange fetches one change (GET /change/<id>).
func (c *Client) GetChange(ctx context.Context, id int) (*Change, error) {
var ch Change
if err := c.call(ctx, http.MethodGet, "/change/"+itoa(id), nil, nil, &ch); err != nil {
return nil, err
}
return &ch, nil
}
// ListChanges searches changes (GET /search/Change/) with forcedisplay
// fields 1 (name), 2 (id), 12 (status). GLPI returns rows as OBJECTS
// KEYED BY FIELD-ID STRING — parsed here into ChangeRow. status 0 lists
// all; any other value filters field 12 with an equals criterion.
func (c *Client) ListChanges(ctx context.Context, status int) ([]ChangeRow, error) {
q := url.Values{}
forced := []string{"1", "2", "12"}
for _, f := range forced {
q.Add("forcedisplay[]", f)
}
if status > 0 {
crit, err := json.Marshal([]map[string]any{{
"field": 12, "searchtype": "equals", "value": status,
}})
if err != nil {
return nil, fmt.Errorf("%w: cannot encode criteria", ErrMalformedResponse)
}
q.Set("criteria", string(crit))
}
var body struct {
Total int `json:"totalcount"`
Data []map[string]any `json:"data"`
}
if err := c.call(ctx, http.MethodGet, "/search/Change", q, nil, &body); err != nil {
return nil, err
}
rows := make([]ChangeRow, 0, len(body.Data))
for _, d := range body.Data {
rows = append(rows, ChangeRow{
Name: asString(d["1"]),
ID: asInt(d["2"]),
Status: asInt(d["12"]),
})
}
return rows, nil
}
// TransitionChange moves a change to a status (PUT /change/<id> with
// {"input":{"status":N}}). GLPI answers 200 with an array whose members
// carry a boolean result — a false anywhere is a failed update.
func (c *Client) TransitionChange(ctx context.Context, id, status int) error {
if status < StatusNew || status > StatusClosed {
return fmt.Errorf("%w: unknown change status %d", ErrValidation, status)
}
payload := map[string]any{"input": map[string]any{"status": status}}
var arr []map[string]any
if err := c.call(ctx, http.MethodPut, "/change/"+itoa(id), nil, payload, &arr); err != nil {
return err
}
for _, m := range arr {
for _, v := range m {
if b, ok := v.(bool); ok && !b {
return fmt.Errorf("%w: transition rejected", ErrValidation)
}
}
}
return nil
}
// AddFollowup appends a followup note to a change (POST /ITILFollowup).
//
// GLPI contract modeled faithfully: this endpoint REQUIRES the input to
// be an ARRAY of objects — {"input":[{...}]} — where the Change-create
// endpoint takes the object form.
func (c *Client) AddFollowup(ctx context.Context, changeID int, content string) error {
if content == "" {
return fmt.Errorf("%w: followup content required", ErrValidation)
}
payload := map[string]any{
"input": []map[string]any{{
"itemtype": "Change",
"items_id": changeID,
"content": content,
}},
}
_, err := c.postCreate(ctx, "/ITILFollowup", payload)
return err
}
// asString coerces a search-row cell (string or number) to string.
func asString(v any) string {
switch s := v.(type) {
case string:
return s
case float64:
return trimFloat(s)
case nil:
return ""
default:
return fmt.Sprint(v)
}
}
// asInt coerces a search-row cell (number or numeric string) to int.
// GLPI search cells arrive as JSON numbers or strings depending on the
// field; both must parse.
func asInt(v any) int {
switch n := v.(type) {
case float64:
return int(n)
case int:
return n
case string:
i, _ := parseLeadingInt(n)
return i
case nil:
return 0
default:
return 0
}
}
+222
View File
@@ -0,0 +1,222 @@
// Package glpi is a stdlib-only client for the GLPI REST API
// (apirest.php). It exists so the harness and every vertical talk to
// the ITSM/CMDB through one Go library instead of python glue: change
// create/list/show/transition, ITIL followups, CI search, and the
// session/profile lifecycle.
//
// Security discipline: authentication travels ONLY in headers —
// App-Token on every request, Authorization: user_token on initSession,
// Session-Token after it. Tokens never appear in flags, logs, or error
// strings; response bodies are never surfaced in error messages (a
// server echo is assumed to be able to carry a token), so errors are
// one-line, parseable "sentinel: http NNN" shapes.
//
// GLPI quirks modeled faithfully:
// - POST create endpoints return an ARRAY: [{"id":N,"message":"..."}].
// - Change create takes {"input":{...}}; ITILFollowup REQUIRES
// {"input":[{...}]}.
// - search rows are objects keyed by field-id string when forcedisplay
// is used ({"1":"name","2":7,"12":3}).
// - initSession -> {"session_token":"..."}; changeActiveProfile
// switches the session's active profile (agent mode).
package glpi
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
)
// Sentinel errors. Wrap-check with errors.Is; every API failure maps to
// exactly one of these plus an "http NNN" code in the message.
var (
ErrUnreachable = errors.New("glpi: unreachable")
ErrMalformedResponse = errors.New("glpi: malformed response")
ErrAuth = errors.New("glpi: auth failed")
ErrNotFound = errors.New("glpi: not found")
ErrValidation = errors.New("glpi: validation failed")
ErrServer = errors.New("glpi: server error")
)
// Config configures a Client.
type Config struct {
BaseURL string // full API endpoint, e.g. https://cmdb.knownelement.com/apirest.php
AppToken string // GLPI App-Token; header on every request, never logged
UserToken string // GLPI user token; Authorization header at initSession, never logged
Timeout time.Duration
}
// Client is a GLPI REST client. It lazily opens a session on the first
// call (InitSession) and re-opens one after KillSession. Safe for
// concurrent use.
type Client struct {
cfg Config
http *http.Client
mu sync.Mutex
session string
}
// New builds a client. A zero Timeout means 30s. No network traffic
// happens until the first call.
func New(cfg Config) *Client {
if cfg.Timeout == 0 {
cfg.Timeout = 30 * time.Second
}
cfg.BaseURL = strings.TrimRight(cfg.BaseURL, "/")
return &Client{cfg: cfg, http: &http.Client{Timeout: cfg.Timeout}}
}
// sessionToken returns the live session token, if any.
func (c *Client) sessionToken() string {
c.mu.Lock()
defer c.mu.Unlock()
return c.session
}
// setSession stores the session token obtained from initSession.
func (c *Client) setSession(tok string) {
c.mu.Lock()
defer c.mu.Unlock()
c.session = tok
}
// InitSession opens a GLPI session (POST /initSession). Called
// automatically on the first API call; public so callers can pre-warm
// and so the profile switch has a session to act on. Idempotent while
// the session is live.
func (c *Client) InitSession(ctx context.Context) error {
if tok := c.sessionToken(); tok != "" {
return nil
}
var resp struct {
SessionToken string `json:"session_token"`
}
if err := c.raw(ctx, http.MethodPost, "/initSession", nil, nil, &resp, true); err != nil {
if errors.Is(err, ErrValidation) {
// GLPI answers 400 (ERROR_GLPI_LOGIN / ERROR_APP_TOKEN_...)
// for bad credentials or a wrong app token — that is an
// auth failure, not a validation failure.
return fmt.Errorf("%w: http 400 (initSession refused)", ErrAuth)
}
return err
}
if resp.SessionToken == "" {
return fmt.Errorf("%w: initSession returned no session_token", ErrMalformedResponse)
}
c.setSession(resp.SessionToken)
return nil
}
// KillSession closes the session server-side (GET /killSession) and
// forgets the local token; the next call transparently re-inits.
func (c *Client) KillSession(ctx context.Context) error {
if err := c.call(ctx, http.MethodGet, "/killSession", nil, nil, nil); err != nil {
return err
}
c.setSession("")
return nil
}
// call performs one authenticated exchange: it ensures a live session,
// then sends the request with Session-Token auth.
func (c *Client) call(ctx context.Context, method, path string, query url.Values, in, out any) error {
if c.sessionToken() == "" {
if err := c.InitSession(ctx); err != nil {
return err
}
}
return c.raw(ctx, method, path, query, in, out, false)
}
// raw performs one JSON exchange. initAuth selects the initSession auth
// flavor (Authorization: user_token) instead of Session-Token. out may
// be nil for bodies the caller does not parse (killSession answers
// `true`, update answers a success array checked separately).
func (c *Client) raw(ctx context.Context, method, path string, query url.Values, in, out any, initAuth bool) error {
var body io.Reader
if in != nil {
b, err := json.Marshal(in)
if err != nil {
return fmt.Errorf("%w: cannot encode request", ErrMalformedResponse)
}
body = strings.NewReader(string(b))
}
u := c.cfg.BaseURL + path
if len(query) > 0 {
u += "?" + query.Encode()
}
req, err := http.NewRequestWithContext(ctx, method, u, body)
if err != nil {
return fmt.Errorf("%w: bad endpoint", ErrUnreachable)
}
// Tokens live in headers and only in headers.
req.Header.Set("App-Token", c.cfg.AppToken)
if initAuth {
req.Header.Set("Authorization", "user_token "+c.cfg.UserToken)
} else if tok := c.sessionToken(); tok != "" {
req.Header.Set("Session-Token", tok)
}
req.Header.Set("Accept", "application/json")
if in != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := c.http.Do(req)
if err != nil {
// Transport errors embed URLs and peer text; drop them all.
return ErrUnreachable
}
defer resp.Body.Close()
raw, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil {
return ErrUnreachable
}
return handleResponse(resp.StatusCode, raw, out)
}
// handleResponse maps one HTTP exchange to typed errors. Response BODIES
// are never surfaced: a server echo is assumed to be able to contain a
// token (see the fakeglpi package, which deliberately echoes it).
func handleResponse(status int, body []byte, out any) error {
switch {
case status >= 200 && status < 300:
if out == nil {
return nil
}
if len(body) == 0 {
return fmt.Errorf("%w: empty body", ErrMalformedResponse)
}
if err := json.Unmarshal(body, out); err != nil {
return fmt.Errorf("%w: body is not valid json", ErrMalformedResponse)
}
return nil
default:
return statusError(status)
}
}
// statusError maps a non-2xx status to a sentinel + parseable one-liner.
func statusError(status int) error {
switch {
case status == http.StatusUnauthorized || status == http.StatusForbidden:
return fmt.Errorf("%w: http %d", ErrAuth, status)
case status == http.StatusNotFound:
return fmt.Errorf("%w: http %d", ErrNotFound, status)
case status == http.StatusUnprocessableEntity || status == http.StatusBadRequest || status == http.StatusConflict:
return fmt.Errorf("%w: http %d", ErrValidation, status)
default:
return fmt.Errorf("%w: http %d", ErrServer, status)
}
}
// itoa is a tiny local alias used across the endpoint files.
func itoa(n int) string { return strconv.Itoa(n) }
+82
View File
@@ -0,0 +1,82 @@
package glpi
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
)
// SearchRow is one CI hit from a search: the well-known fields 2 (id)
// and 1 (name) plus the raw row keyed by field-id string, exactly as
// GLPI returns it under forcedisplay.
type SearchRow struct {
ID int
Name string
Fields map[string]any
}
// SearchCI searches any itemtype's CIs (GET /search/<itemtype>) with a
// contains criterion on field 1 (name) and forcedisplay 1,2.
func (c *Client) SearchCI(ctx context.Context, itemtype, term string) ([]SearchRow, error) {
if itemtype == "" {
return nil, fmt.Errorf("%w: itemtype required", ErrValidation)
}
q := url.Values{}
q.Add("forcedisplay[]", "1")
q.Add("forcedisplay[]", "2")
if term != "" {
crit, err := json.Marshal([]map[string]any{{
"field": 1, "searchtype": "contains", "value": term,
}})
if err != nil {
return nil, fmt.Errorf("%w: cannot encode criteria", ErrMalformedResponse)
}
q.Set("criteria", string(crit))
}
var body struct {
Total int `json:"totalcount"`
Data []map[string]any `json:"data"`
}
if err := c.call(ctx, http.MethodGet, "/search/"+esc(itemtype), q, nil, &body); err != nil {
return nil, err
}
rows := make([]SearchRow, 0, len(body.Data))
for _, d := range body.Data {
rows = append(rows, SearchRow{
Name: asString(d["1"]),
ID: asInt(d["2"]),
Fields: d,
})
}
return rows, nil
}
// GetItem fetches one CI of any itemtype raw (GET /<itemtype>/<id>),
// used by `ci show`. The full server object is returned untouched.
func (c *Client) GetItem(ctx context.Context, itemtype string, id int) (map[string]any, error) {
var obj map[string]any
if err := c.call(ctx, http.MethodGet, "/"+esc(itemtype)+"/"+itoa(id), nil, nil, &obj); err != nil {
return nil, err
}
return obj, nil
}
// esc path-escapes an itemtype.
func esc(s string) string { return url.PathEscape(s) }
// eqfold is strings.EqualFold kept local for the status table.
func eqfold(a, b string) bool { return strings.EqualFold(a, b) }
// trimFloat renders a JSON number without a trailing ".0".
func trimFloat(f float64) string {
return strconv.FormatFloat(f, 'f', -1, 64)
}
// parseLeadingInt parses an int from a possibly messy search cell.
func parseLeadingInt(s string) (int, error) {
return strconv.Atoi(strings.TrimSpace(s))
}
+39
View File
@@ -0,0 +1,39 @@
package glpi
import (
"context"
"fmt"
"net/http"
)
// Profile is one GLPI profile of the logged-in user (GET /getMyProfiles,
// GET /Profile/<id>). IsActive reflects the session's active profile.
type Profile struct {
ID int `json:"id"`
Name string `json:"name"`
IsActive bool `json:"is_active"`
}
// GetMyProfiles lists the profiles of the logged-in user. GLPI answers
// with a bare JSON array (not a wrapped object).
func (c *Client) GetMyProfiles(ctx context.Context) ([]Profile, error) {
var profiles []Profile
if err := c.call(ctx, http.MethodGet, "/getMyProfiles", nil, nil, &profiles); err != nil {
return nil, err
}
return profiles, nil
}
// ChangeActiveProfile switches the session's active profile
// (POST /changeActiveProfile with {"profiles_id":N}). Agent mode uses
// this to move into the right role (e.g. 5 = Hotliner) after
// InitSession; servers that gate operations per profile then accept the
// calls that were previously rejected.
func (c *Client) ChangeActiveProfile(ctx context.Context, profileID int) error {
if profileID <= 0 {
return fmt.Errorf("%w: profile id must be positive", ErrValidation)
}
payload := map[string]any{"profiles_id": profileID}
// The endpoint answers `true` — nothing to parse.
return c.call(ctx, http.MethodPost, "/changeActiveProfile", nil, payload, nil)
}
+530
View File
@@ -0,0 +1,530 @@
// Package glpi is a stdlib-only client for the GLPI REST API
// (apirest.php). Tests run against the stateful in-process fake
// (internal/fakeglpi); the real CMDB is NEVER contacted.
package glpi_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"testing"
"time"
"git.knownelement.com/ukrrs/mopac-glpi-go/glpi"
"git.knownelement.com/ukrrs/mopac-glpi-go/internal/fakeglpi"
)
const (
appTok = "fake-app-token-0123456789"
userTok = "fake-user-token-0123456789"
sessSeed = "sess-" // fake session tokens carry this prefix
)
func newClient(t *testing.T) (*glpi.Client, *fakeglpi.Server) {
t.Helper()
srv := fakeglpi.New(appTok, userTok)
t.Cleanup(srv.Close)
c := glpi.New(glpi.Config{BaseURL: srv.URL, AppToken: appTok, UserToken: userTok, Timeout: 5 * time.Second})
return c, srv
}
func lastReq(t *testing.T, srv *fakeglpi.Server) fakeglpi.Request {
t.Helper()
reqs := srv.Requests()
if len(reqs) == 0 {
t.Fatal("no requests recorded")
}
return reqs[len(reqs)-1]
}
// --- session lifecycle + header discipline ---------------------------------
// GLPI auth is three headers: App-Token on EVERY request, Authorization
// user_token ONLY on initSession, Session-Token on everything after.
func TestSessionHeaderDiscipline(t *testing.T) {
c, srv := newClient(t)
if _, err := c.GetMyProfiles(context.Background()); err != nil {
t.Fatalf("GetMyProfiles: %v", err)
}
initReq := srv.Requests()[0]
if initReq.Method != "POST" || initReq.Path != "/initSession" {
t.Fatalf("first request = %+v, want POST /initSession", initReq)
}
if initReq.AuthHeader != "user_token "+userTok {
t.Errorf("initSession Authorization = %q", initReq.AuthHeader)
}
if initReq.SessionToken != "" {
t.Errorf("initSession must not carry a Session-Token: %q", initReq.SessionToken)
}
for i, r := range srv.Requests() {
if r.AppToken != appTok {
t.Errorf("request %d App-Token = %q, want the app token", i, r.AppToken)
}
if i > 0 {
if r.AuthHeader != "" {
t.Errorf("request %d carries Authorization after init: %q", i, r.AuthHeader)
}
if !strings.HasPrefix(r.SessionToken, sessSeed) {
t.Errorf("request %d Session-Token = %q, want a fake session token", i, r.SessionToken)
}
}
}
}
func TestInitSessionParsesSessionToken(t *testing.T) {
c, _ := newClient(t)
if err := c.InitSession(context.Background()); err != nil {
t.Fatalf("InitSession: %v", err)
}
if err := c.InitSession(context.Background()); err != nil {
t.Fatalf("second InitSession must reuse/be idempotent: %v", err)
}
}
func TestKillSessionAndReinit(t *testing.T) {
c, srv := newClient(t)
if _, err := c.GetMyProfiles(context.Background()); err != nil {
t.Fatalf("warmup: %v", err)
}
if got := srv.SessionCount(); got != 1 {
t.Fatalf("sessions = %d, want 1", got)
}
if err := c.KillSession(context.Background()); err != nil {
t.Fatalf("KillSession: %v", err)
}
if got := srv.SessionCount(); got != 0 {
t.Fatalf("sessions after kill = %d, want 0", got)
}
// The next call transparently re-inits with a fresh session.
if _, err := c.GetMyProfiles(context.Background()); err != nil {
t.Fatalf("call after kill: %v", err)
}
if got := srv.SessionCount(); got != 1 {
t.Fatalf("sessions after re-init = %d, want 1", got)
}
}
// --- change create (array response + object input) --------------------------
func TestCreateChangeRoundTrip(t *testing.T) {
c, srv := newClient(t)
id, err := c.CreateChange(context.Background(), "Quota: per-identity accounting", "<p>scope body</p>", 3, 4)
if err != nil {
t.Fatalf("CreateChange: %v", err)
}
if id == 0 {
t.Fatal("created id = 0")
}
// The POST body must carry input as a single OBJECT (GLPI Change
// contract; ITILFollowup is the array-flavored endpoint).
body := lastReq(t, srv).Body
if !strings.HasPrefix(body, `{"input":{`) {
t.Fatalf("POST body = %s, want {\"input\":{...}} (object, not array)", body)
}
var p struct {
Input struct {
Name string `json:"name"`
Content string `json:"content"`
Urgency int `json:"urgency"`
Impact int `json:"impact"`
} `json:"input"`
}
if err := json.Unmarshal([]byte(body), &p); err != nil {
t.Fatalf("POST body: %v", err)
}
if p.Input.Name != "Quota: per-identity accounting" || p.Input.Content != "<p>scope body</p>" ||
p.Input.Urgency != 3 || p.Input.Impact != 4 {
t.Errorf("POST input = %+v", p.Input)
}
stored, ok := srv.Change(id)
if !ok || stored.Name != "Quota: per-identity accounting" || stored.Urgency != 3 || stored.Impact != 4 {
t.Errorf("stored = %+v", stored)
}
if stored.Status != glpi.StatusNew {
t.Errorf("default status = %d, want %d (new)", stored.Status, glpi.StatusNew)
}
got, err := c.GetChange(context.Background(), id)
if err != nil {
t.Fatalf("GetChange: %v", err)
}
if got.ID != id || got.Name != stored.Name || got.Content != "<p>scope body</p>" ||
got.Status != glpi.StatusNew || got.Urgency != 3 || got.Impact != 4 {
t.Errorf("GetChange = %+v", got)
}
if _, err := c.GetChange(context.Background(), 424242); !errors.Is(err, glpi.ErrNotFound) {
t.Errorf("missing change err = %v, want ErrNotFound", err)
}
}
func TestCreateChangeValidation(t *testing.T) {
c, _ := newClient(t)
tests := []struct {
name string
title string
urgency int
impact int
}{
{"empty title", "", 3, 3},
{"urgency too low", "x", 0, 3},
{"urgency too high", "x", 6, 3},
{"impact too low", "x", 3, 0},
{"impact too high", "x", 3, 6},
}
for _, tt := range tests {
if _, err := c.CreateChange(context.Background(), tt.title, "c", tt.urgency, tt.impact); !errors.Is(err, glpi.ErrValidation) {
t.Errorf("%s: err = %v, want ErrValidation", tt.name, err)
}
}
}
// The fake itself must enforce the array-vs-object input quirks on the
// wire: Change takes {"input":{...}}, ITILFollowup REQUIRES
// {"input":[{...}]} and rejects the object form.
func TestFakeInputShapeQuirks(t *testing.T) {
c, srv := newClient(t)
id, err := c.CreateChange(context.Background(), "seed", "c", 3, 3)
if err != nil || id == 0 {
t.Fatalf("seed: %d %v", id, err)
}
sess := srv.Sessions()[0]
post := func(path, body string) int {
t.Helper()
req, _ := http.NewRequest("POST", srv.URL+path, strings.NewReader(body))
req.Header.Set("App-Token", appTok)
req.Header.Set("Session-Token", sess)
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("POST %s: %v", path, err)
}
defer resp.Body.Close()
return resp.StatusCode
}
if got := post("/change/", `{"input":[{"name":"array form"}]}`); got != 400 {
t.Errorf("change create with array input = %d, want 400", got)
}
if got := post("/ITILFollowup/", `{"input":{"content":"object form"}}`); got != 400 {
t.Errorf("followup with object input = %d, want 400", got)
}
body := fmt.Sprintf(`{"input":[{"itemtype":"Change","items_id":%d,"content":"ok"}]}`, id)
if got := post("/ITILFollowup/", body); got != 201 {
t.Errorf("followup with array input = %d, want 201", got)
}
}
// --- list (keyed search rows) ------------------------------------------------
func TestListChanges(t *testing.T) {
c, srv := newClient(t)
a := srv.AddChange(fakeglpi.Change{Name: "new one", Status: glpi.StatusNew, Urgency: 3, Impact: 3})
b := srv.AddChange(fakeglpi.Change{Name: "solved one", Status: glpi.StatusSolved, Urgency: 3, Impact: 3})
rows, err := c.ListChanges(context.Background(), 0)
if err != nil {
t.Fatalf("ListChanges: %v", err)
}
if len(rows) != 2 || rows[0].ID != a || rows[1].ID != b {
t.Fatalf("rows = %+v, want ids %d,%d", rows, a, b)
}
if rows[0].Name != "new one" || rows[0].Status != glpi.StatusNew {
t.Errorf("row0 = %+v", rows[0])
}
wantQ := "forcedisplay%5B%5D=1&forcedisplay%5B%5D=2&forcedisplay%5B%5D=12"
if q := lastReq(t, srv).Query; q != wantQ {
t.Errorf("query = %q, want %q", q, wantQ)
}
rows, err = c.ListChanges(context.Background(), glpi.StatusNew)
if err != nil {
t.Fatalf("ListChanges(status): %v", err)
}
if len(rows) != 1 || rows[0].ID != a {
t.Fatalf("filtered rows = %+v, want only %d", rows, a)
}
q := lastReq(t, srv).Query
for _, frag := range []string{
`criteria=%5B%7B%22field%22%3A12`, // criteria=[{"field":12
`%22searchtype%22%3A%22equals%22`, // ,"searchtype":"equals"
`%22value%22%3A1%7D%5D`, // ,"value":1}]
"forcedisplay%5B%5D=1",
} {
if !strings.Contains(q, frag) {
t.Errorf("query %q missing %q", q, frag)
}
}
}
// --- transition ---------------------------------------------------------------
func TestTransitionChange(t *testing.T) {
c, srv := newClient(t)
id := srv.AddChange(fakeglpi.Change{Name: "flow", Status: glpi.StatusNew, Urgency: 3, Impact: 3})
if err := c.TransitionChange(context.Background(), id, glpi.StatusSolved); err != nil {
t.Fatalf("TransitionChange: %v", err)
}
if body := lastReq(t, srv).Body; body != `{"input":{"status":11}}` {
t.Errorf("PUT body = %s", body)
}
if got, _ := srv.Change(id); got.Status != glpi.StatusSolved {
t.Errorf("stored status = %d, want %d", got.Status, glpi.StatusSolved)
}
err := c.TransitionChange(context.Background(), 424242, glpi.StatusSolved)
if !errors.Is(err, glpi.ErrNotFound) || !strings.Contains(err.Error(), "http 404") {
t.Errorf("missing-change transition err = %v", err)
}
}
// --- followup (array-of-objects input) ----------------------------------------
func TestAddFollowup(t *testing.T) {
c, srv := newClient(t)
id := srv.AddChange(fakeglpi.Change{Name: "with note", Status: glpi.StatusNew, Urgency: 3, Impact: 3})
if err := c.AddFollowup(context.Background(), id, "REPORT delivered: smoke"); err != nil {
t.Fatalf("AddFollowup: %v", err)
}
wantBody := fmt.Sprintf(`{"input":[{"content":"REPORT delivered: smoke","items_id":%d,"itemtype":"Change"}]}`, id)
if body := lastReq(t, srv).Body; body != wantBody {
t.Errorf("POST body = %s, want %s", body, wantBody)
}
fups := srv.Followups(id)
if len(fups) != 1 || fups[0].Content != "REPORT delivered: smoke" || fups[0].Itemtype != "Change" {
t.Errorf("followups = %+v", fups)
}
if err := c.AddFollowup(context.Background(), 424242, "nowhere"); !errors.Is(err, glpi.ErrValidation) {
t.Errorf("followup on missing change err = %v, want ErrValidation", err)
}
}
// --- CI search + raw item fetch ----------------------------------------------
func TestSearchCI(t *testing.T) {
c, srv := newClient(t)
web := srv.AddItem("Computer", map[string]any{"name": "web-01", "serial": "ABC123"})
_ = srv.AddItem("Computer", map[string]any{"name": "db-01"})
_ = srv.AddItem("Monitor", map[string]any{"name": "web-cam"})
rows, err := c.SearchCI(context.Background(), "Computer", "web")
if err != nil {
t.Fatalf("SearchCI: %v", err)
}
if len(rows) != 1 || rows[0].ID != web || rows[0].Name != "web-01" {
t.Fatalf("rows = %+v, want the web-01 computer", rows)
}
if rows[0].Fields["1"] != "web-01" {
t.Errorf("row fields = %+v, want field \"1\" keyed name", rows[0].Fields)
}
q := lastReq(t, srv).Query
for _, frag := range []string{`%22field%22%3A1`, `%22searchtype%22%3A%22contains%22`, `%22value%22%3A%22web%22`, "forcedisplay%5B%5D=1", "forcedisplay%5B%5D=2"} {
if !strings.Contains(q, frag) {
t.Errorf("query %q missing %q", q, frag)
}
}
if rows, err := c.SearchCI(context.Background(), "Computer", "no-such-thing"); err != nil || len(rows) != 0 {
t.Errorf("no-match search = %+v err %v, want empty", rows, err)
}
}
func TestGetItem(t *testing.T) {
c, srv := newClient(t)
id := srv.AddItem("Computer", map[string]any{"name": "web-01", "serial": "ABC123"})
raw, err := c.GetItem(context.Background(), "Computer", id)
if err != nil {
t.Fatalf("GetItem: %v", err)
}
if raw["name"] != "web-01" || raw["serial"] != "ABC123" {
t.Errorf("raw = %+v", raw)
}
if _, err := c.GetItem(context.Background(), "Computer", 424242); !errors.Is(err, glpi.ErrNotFound) {
t.Errorf("missing item err = %v, want ErrNotFound", err)
}
}
// --- profiles + agent-mode switch ----------------------------------------------
func TestProfiles(t *testing.T) {
c, srv := newClient(t)
profs, err := c.GetMyProfiles(context.Background())
if err != nil {
t.Fatalf("GetMyProfiles: %v", err)
}
if len(profs) != 3 {
t.Fatalf("profiles = %+v, want 3", profs)
}
active := 0
for _, p := range profs {
if p.IsActive {
active = p.ID
}
}
if active != 6 { // Super-admin is the fake's default active profile
t.Errorf("default active profile = %d, want 6", active)
}
if err := c.ChangeActiveProfile(context.Background(), 5); err != nil {
t.Fatalf("ChangeActiveProfile: %v", err)
}
if body := lastReq(t, srv).Body; body != `{"profiles_id":5}` {
t.Errorf("changeActiveProfile body = %s", body)
}
profs, _ = c.GetMyProfiles(context.Background())
for _, p := range profs {
if p.ID == 5 && !p.IsActive {
t.Errorf("profile 5 not active after switch: %+v", profs)
}
if p.ID == 6 && p.IsActive {
t.Errorf("profile 6 still active after switch: %+v", profs)
}
}
if err := c.ChangeActiveProfile(context.Background(), 999); !errors.Is(err, glpi.ErrValidation) {
t.Errorf("unknown profile err = %v, want ErrValidation", err)
}
}
// THE agent-mode proof: with RequireChangeProfile=5 the fake rejects
// change creation until the session's active profile IS 5 — the exact
// Hotliner flow an agent env file drives via MGLPI_PROFILE_ID.
func TestRequireProfileAgentMode(t *testing.T) {
c, srv := newClient(t)
srv.RequireChangeProfile = 5
_, err := c.CreateChange(context.Background(), "before switch", "c", 3, 3)
if !errors.Is(err, glpi.ErrAuth) || !strings.Contains(err.Error(), "http 403") {
t.Fatalf("pre-switch err = %v, want ErrAuth http 403", err)
}
if err := c.ChangeActiveProfile(context.Background(), 5); err != nil {
t.Fatalf("ChangeActiveProfile(5): %v", err)
}
id, err := c.CreateChange(context.Background(), "after switch", "c", 3, 3)
if err != nil || id == 0 {
t.Fatalf("post-switch create = %d, %v; want success", id, err)
}
}
// --- error mapping / transport ------------------------------------------------
func TestErrorMapping(t *testing.T) {
tests := []struct {
name string
fail fakeglpi.FailSpec
want error
}{
{"400", fakeglpi.FailSpec{Status: 400, Body: `[{"ERROR_ARGUMENTS":"bad %s"}]`}, glpi.ErrValidation},
{"401", fakeglpi.FailSpec{Status: 401, Body: `[{"ERROR_SESSION_TOKEN_MISSING":"%s"}]`}, glpi.ErrAuth},
{"403", fakeglpi.FailSpec{Status: 403, Body: `[{"ERROR_RIGHT_MISSING":"%s"}]`}, glpi.ErrAuth},
{"404", fakeglpi.FailSpec{Status: 404, Body: `[{"ERROR_ITEM_NOT_FOUND":"%s"}]`}, glpi.ErrNotFound},
{"422", fakeglpi.FailSpec{Status: 422, Body: `[{"ERROR_GLPI_ADD":"%s"}]`}, glpi.ErrValidation},
{"500", fakeglpi.FailSpec{Status: 500, Body: `boom %s`}, glpi.ErrServer},
{"502", fakeglpi.FailSpec{Status: 502, Body: `bad gateway %s`}, glpi.ErrServer},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c, srv := newClient(t)
// Warm the session first: Fail is consumed by the first
// request that sees it, and the first request is always the
// initSession — the mapping under test is the endpoint's.
if _, err := c.GetMyProfiles(context.Background()); err != nil {
t.Fatalf("warmup: %v", err)
}
srv.Fail = &tt.fail
_, err := c.GetMyProfiles(context.Background())
if !errors.Is(err, tt.want) {
t.Fatalf("err = %v, want %v", err, tt.want)
}
if !strings.Contains(err.Error(), "http "+strconv.Itoa(tt.fail.Status)) {
t.Fatalf("err = %q, want embedded http status", err.Error())
}
})
}
}
func TestUnreachable(t *testing.T) {
srv := fakeglpi.New(appTok, userTok)
url := srv.URL
srv.Close() // port now dead
c := glpi.New(glpi.Config{BaseURL: url, AppToken: appTok, UserToken: userTok, Timeout: 2 * time.Second})
_, err := c.GetMyProfiles(context.Background())
if !errors.Is(err, glpi.ErrUnreachable) {
t.Fatalf("err = %v, want ErrUnreachable", err)
}
if strings.Contains(err.Error(), "http") {
t.Fatalf("unreachable err should not fake an http status: %q", err.Error())
}
}
func TestMalformedResponse(t *testing.T) {
c, srv := newClient(t)
srv.Fail = &fakeglpi.FailSpec{Status: 200, Body: `<<not json>>`}
if _, err := c.GetMyProfiles(context.Background()); !errors.Is(err, glpi.ErrMalformedResponse) {
t.Fatalf("err = %v, want ErrMalformedResponse", err)
}
}
// --- redaction: the fake echoes presented tokens in every error body; ---
// --- surviving that proves the client never surfaces them. ---
func TestTokensNeverLeak(t *testing.T) {
t.Run("wrong user token rejected without echo", func(t *testing.T) {
srv := fakeglpi.New(appTok, userTok)
t.Cleanup(srv.Close)
c := glpi.New(glpi.Config{BaseURL: srv.URL, AppToken: appTok, UserToken: "wrong-user-token", Timeout: 2 * time.Second})
_, err := c.GetMyProfiles(context.Background())
if !errors.Is(err, glpi.ErrAuth) {
t.Fatalf("err = %v, want ErrAuth", err)
}
if strings.Contains(err.Error(), "wrong-user-token") || strings.Contains(err.Error(), userTok) || strings.Contains(err.Error(), appTok) {
t.Fatalf("error leaks a token: %q", err.Error())
}
})
t.Run("error bodies never surfaced", func(t *testing.T) {
c, srv := newClient(t)
srv.Fail = &fakeglpi.FailSpec{Status: 500, Body: `crashed holding %s %s-echo`}
_, err := c.GetMyProfiles(context.Background())
if strings.Contains(err.Error(), "crashed") ||
strings.Contains(err.Error(), userTok) || strings.Contains(err.Error(), appTok) ||
strings.Contains(err.Error(), sessSeed) {
t.Fatalf("err = %q, want sanitized one-liner", err.Error())
}
})
t.Run("tokens travel only in headers", func(t *testing.T) {
c, srv := newClient(t)
id, err := c.CreateChange(context.Background(), "header audit", "c", 3, 3)
if err != nil || id == 0 {
t.Fatalf("CreateChange: %d %v", id, err)
}
if err := c.AddFollowup(context.Background(), id, "note"); err != nil {
t.Fatalf("AddFollowup: %v", err)
}
for i, r := range srv.Requests() {
for _, in := range []string{r.Body, r.Query, r.Path} {
if strings.Contains(in, appTok) || strings.Contains(in, userTok) || strings.Contains(in, sessSeed) {
t.Fatalf("request %d carries a token outside headers: %+v", i, r)
}
}
}
})
}
// --- status helpers -----------------------------------------------------------
func TestStatusHelpers(t *testing.T) {
if got := glpi.StatusName(glpi.StatusNew); got != "new" {
t.Errorf("StatusName(1) = %q", got)
}
if id, ok := glpi.StatusID("solved"); !ok || id != glpi.StatusSolved {
t.Errorf("StatusID(solved) = %d %v", id, ok)
}
if _, ok := glpi.StatusID("bogus"); ok {
t.Error("StatusID(bogus) accepted")
}
}
+3
View File
@@ -0,0 +1,3 @@
module git.knownelement.com/ukrrs/mopac-glpi-go
go 1.26
+173
View File
@@ -0,0 +1,173 @@
// Package cli implements the mglpi command line: a thin, machine-friendly
// front end over the glpi library. Connection settings come from
// MGLPI_URL / MGLPI_APP_TOKEN / MGLPI_USER_TOKEN env vars (plus optional
// MGLPI_PROFILE_ID for agent mode) or a 0600 --config env file — tokens
// are never flag values and never logged. Every command accepts -o json
// for machine output. Exit codes: 0 ok, 1 usage/config, 2 API error
// (single-line stderr carrying the http status, parseable).
package cli
import (
"flag"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"git.knownelement.com/ukrrs/mopac-glpi-go/internal/config"
"git.knownelement.com/ukrrs/mopac-glpi-go/glpi"
)
const usage = `mglpi: GLPI/CMDB CLI (stdlib-only, library-backed)
Usage:
mglpi whoami [-o json]
mglpi change create --title T [--urgency N] [--impact N] [--profile N]
[--content FILE|-] [-o json]
mglpi change show ID [-o json]
mglpi change list [--status N|NAME] [-o json]
mglpi change transition ID STATUS (STATUS numeric or: new evaluation
approval test qualification waiting accepted assigned
planned pending solved closed) [-o json]
mglpi change followup ID [--content FILE|-] [-o json]
mglpi ci search TYPE TERM [-o json]
mglpi ci show TYPE ID [-o json]
mglpi help
Connection: MGLPI_URL + MGLPI_APP_TOKEN + MGLPI_USER_TOKEN env vars, or
--config PATH pointing at a 0600 env file with the same keys. Tokens
never appear in flags, logs, or error output.
Agent mode: --profile N (or MGLPI_PROFILE_ID in the env file) switches
the session's active profile (e.g. 5 = Hotliner) right after
InitSession — servers that gate operations per profile then accept the
calls. whoami never switches.
change create / change followup read their body from stdin by default
(--content FILE to read a file instead).
Exit codes: 0 ok, 1 usage/config error, 2 API error (stderr: one line,
"http NNN" included).`
// Run executes one command; it returns the process exit code.
func Run(args []string, stdout, stderr io.Writer) int {
if len(args) == 0 {
fmt.Fprint(stderr, usage)
return 1
}
// Hoist a leading global --config PATH onto the subcommand (the
// subcommand flag sets already accept it anywhere).
var hoisted []string
for len(args) >= 2 && (args[0] == "--config" || args[0] == "-config") {
hoisted = append(hoisted, args[0], args[1])
args = args[2:]
}
if len(hoisted) > 0 {
if len(args) == 0 {
fmt.Fprint(stderr, usage)
return 1
}
args = append(args, hoisted...)
}
switch args[0] {
case "help", "-h", "--help":
fmt.Fprint(stdout, usage)
return 0
case "whoami":
return cmdWhoami(args[1:], stdout, stderr)
case "change":
return cmdChange(args[1:], stdout, stderr)
case "ci":
return cmdCI(args[1:], stdout, stderr)
default:
fmt.Fprintf(stderr, "mglpi: unknown command %q\n\n%s\n", args[0], usage)
return 1
}
}
// newFlags builds a quiet flag set with the shared --config and -o flags.
func newFlags(name string, stderr io.Writer) (*flag.FlagSet, *string, *string) {
fs := flag.NewFlagSet(name, flag.ContinueOnError)
fs.SetOutput(io.Discard)
cfg := fs.String("config", "", "env file with MGLPI_URL/MGLPI_APP_TOKEN/MGLPI_USER_TOKEN (must be 0600)")
out := fs.String("o", "text", "output format: text|json")
return fs, cfg, out
}
// parseArgs parses flags that may appear AFTER positionals (the standard
// flag package stops at the first positional; mglpi's documented surface
// is "change show ID -o json", "ci search TYPE TERM"). It returns the
// positional arguments.
func parseArgs(fs *flag.FlagSet, args []string) ([]string, error) {
var positionals []string
rest := args
for {
if err := fs.Parse(rest); err != nil {
return nil, err
}
got := fs.Args()
i := 0
for i < len(got) && (got[i] == "-" || !strings.HasPrefix(got[i], "-")) {
i++
}
positionals = append(positionals, got[:i]...)
if i == len(got) {
return positionals, nil
}
rest = got[i:]
}
}
// client resolves config (env + optional 0600 file) and builds the
// client, resolving the effective agent profile (flag wins over the
// MGLPI_PROFILE_ID config key). A non-nil error means exit 1; profile
// application (an API op) surfaces later as exit 2.
func client(cfgPath string, profileFlag int) (*glpi.Client, int, error) {
if cfgPath == "" {
cfgPath = os.Getenv("MGLPI_CONFIG")
}
if cfgPath == "" {
if home, err := os.UserHomeDir(); err == nil {
cand := filepath.Join(home, ".config", "mglpi", "env")
if _, err := os.Stat(cand); err == nil {
cfgPath = cand
}
}
}
cfg, _, err := config.Load(cfgPath)
if err != nil {
return nil, 0, err
}
profile := profileFlag
if profile == 0 {
profile = cfg.ProfileID
}
return glpi.New(glpi.Config{
BaseURL: cfg.BaseURL,
AppToken: cfg.AppToken,
UserToken: cfg.UserToken,
}), profile, nil
}
// apiErr reports an API failure the mglpi way: one line, exit 2.
func apiErr(stderr io.Writer, err error) int {
fmt.Fprintf(stderr, "mglpi: %v\n", err)
return 2
}
// usageErr reports a usage/config failure: one line, exit 1.
func usageErr(stderr io.Writer, format string, args ...any) int {
fmt.Fprintf(stderr, "mglpi: "+format+"\n", args...)
return 1
}
// emitJSON pretty-prints v for -o json.
func emitJSON(stdout io.Writer, v any) {
b, err := marshalIndent(v)
if err != nil {
return // library types are JSON-clean by construction
}
stdout.Write(b)
fmt.Fprintln(stdout)
}
+385
View File
@@ -0,0 +1,385 @@
package cli
import (
"encoding/json"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"git.knownelement.com/ukrrs/mopac-glpi-go/internal/fakeglpi"
)
const (
testApp = "fake-app-token-0123456789"
testUser = "fake-user-token-0123456789"
)
func boot(t *testing.T) *fakeglpi.Server {
t.Helper()
srv := fakeglpi.New(testApp, testUser)
t.Cleanup(srv.Close)
t.Setenv("MGLPI_URL", srv.URL)
t.Setenv("MGLPI_APP_TOKEN", testApp)
t.Setenv("MGLPI_USER_TOKEN", testUser)
t.Setenv("MGLPI_PROFILE_ID", "")
return srv
}
func run(t *testing.T, args ...string) (string, string, int) {
t.Helper()
var out, errb strings.Builder
code := Run(args, &out, &errb)
return out.String(), errb.String(), code
}
func contentFile(t *testing.T, content string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "content.txt")
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
return path
}
func TestUsageErrors(t *testing.T) {
boot(t)
tests := []struct {
name string
args []string
}{
{"no args", nil},
{"unknown command", []string{"frobnicate"}},
{"change alone", []string{"change"}},
{"change create without title", []string{"change", "create"}},
{"change show without id", []string{"change", "show"}},
{"change show non-numeric id", []string{"change", "show", "abc"}},
{"change transition bad status name", []string{"change", "transition", "5", "bogus"}},
{"change list bad status name", []string{"change", "list", "--status", "bogus"}},
{"ci search without term", []string{"ci", "search", "Computer"}},
{"ci show without id", []string{"ci", "show", "Computer"}},
{"whoami with positional", []string{"whoami", "extra"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
out, errb, code := run(t, tt.args...)
if code != 1 {
t.Fatalf("code = %d (out %q, err %q), want 1", code, out, errb)
}
if out != "" {
t.Errorf("usage error wrote to stdout: %q", out)
}
if errb == "" {
t.Errorf("no diagnostic on stderr")
}
})
}
}
func TestConfigErrorIsExitOne(t *testing.T) {
boot(t)
t.Setenv("MGLPI_URL", "")
t.Setenv("MGLPI_APP_TOKEN", "")
t.Setenv("MGLPI_USER_TOKEN", "")
_, errb, code := run(t, "change", "list")
if code != 1 {
t.Fatalf("code = %d, want 1 (config)", code)
}
if !strings.Contains(errb, "MGLPI_URL") {
t.Fatalf("stderr = %q", errb)
}
}
func TestWhoami(t *testing.T) {
boot(t)
out, errb, code := run(t, "whoami")
if code != 0 {
t.Fatalf("code = %d, stderr = %q", code, errb)
}
for _, want := range []string{"Self-Service", "Hotliner", "Super-admin", "active"} {
if !strings.Contains(out, want) {
t.Errorf("whoami output missing %q:\n%s", want, out)
}
}
out, _, code = run(t, "whoami", "-o", "json")
if code != 0 {
t.Fatalf("json whoami code %d", code)
}
var got struct {
Profiles []struct {
ID int `json:"id"`
Name string `json:"name"`
IsActive bool `json:"is_active"`
} `json:"profiles"`
}
if err := json.Unmarshal([]byte(out), &got); err != nil || len(got.Profiles) != 3 {
t.Errorf("json whoami = %q err %v", out, err)
}
}
func TestChangeCreateFullFlags(t *testing.T) {
srv := boot(t)
content := contentFile(t, "<p>scope body</p>")
out, errb, code := run(t, "change", "create",
"--title", "Quota: per-identity accounting",
"--content", content,
"--urgency", "3", "--impact", "4",
"-o", "json")
if code != 0 {
t.Fatalf("code = %d, stderr = %q", code, errb)
}
var got struct {
Change struct {
ID int `json:"id"`
} `json:"change"`
}
if err := json.Unmarshal([]byte(out), &got); err != nil || got.Change.ID == 0 {
t.Fatalf("stdout not json: %v (%q)", err, out)
}
stored, ok := srv.Change(got.Change.ID)
if !ok || stored.Name != "Quota: per-identity accounting" || stored.Content != "<p>scope body</p>" ||
stored.Urgency != 3 || stored.Impact != 4 || stored.Status != fakeglpi.StatusNew {
t.Errorf("stored = %+v", stored)
}
}
func TestChangeCreateRequiresTitle(t *testing.T) {
boot(t)
_, errb, code := run(t, "change", "create")
if code != 1 || !strings.Contains(errb, "--title") {
t.Fatalf("code = %d stderr = %q, want usage naming --title", code, errb)
}
}
func TestChangeList(t *testing.T) {
srv := boot(t)
open := srv.AddChange(fakeglpi.Change{Name: "open one", Status: fakeglpi.StatusNew, Urgency: 3, Impact: 3})
solved := srv.AddChange(fakeglpi.Change{Name: "solved one", Status: fakeglpi.StatusSolved, Urgency: 3, Impact: 3})
out, errb, code := run(t, "change", "list")
if code != 0 {
t.Fatalf("code = %d, stderr = %q", code, errb)
}
if !strings.Contains(out, "open one") || !strings.Contains(out, strconv.Itoa(open)) {
t.Errorf("text list = %q", out)
}
out, _, code = run(t, "change", "list", "--status", "solved")
if code != 0 || !strings.Contains(out, "solved one") || strings.Contains(out, "open one") {
t.Errorf("status filter = %q code %d", out, code)
}
out, _, code = run(t, "change", "list", "--status", strconv.Itoa(fakeglpi.StatusNew))
if code != 0 || !strings.Contains(out, "open one") || strings.Contains(out, "solved one") {
t.Errorf("numeric status filter = %q code %d", out, code)
}
out, _, code = run(t, "change", "list", "-o", "json")
if code != 0 {
t.Fatalf("json list code %d", code)
}
var arr struct {
Changes []struct {
ID int `json:"id"`
Name string `json:"name"`
Status int `json:"status"`
} `json:"changes"`
}
if err := json.Unmarshal([]byte(out), &arr); err != nil || len(arr.Changes) != 2 || arr.Changes[0].ID != open || arr.Changes[1].Status != fakeglpi.StatusSolved {
t.Errorf("json list = %q err %v", out, err)
}
_ = solved
}
func TestChangeShow(t *testing.T) {
srv := boot(t)
id := srv.AddChange(fakeglpi.Change{Name: "shown change", Content: "body text", Status: fakeglpi.StatusAssigned, Urgency: 4, Impact: 3})
out, errb, code := run(t, "change", "show", strconv.Itoa(id))
if code != 0 {
t.Fatalf("code = %d, stderr = %q", code, errb)
}
for _, want := range []string{strconv.Itoa(id), "shown change", "body text", "assigned", "4"} {
if !strings.Contains(out, want) {
t.Errorf("show output missing %q:\n%s", want, out)
}
}
out, _, code = run(t, "change", "show", strconv.Itoa(id), "-o", "json")
if code != 0 {
t.Fatalf("json show code %d", code)
}
var got struct {
Change struct {
ID int `json:"id"`
Name string `json:"name"`
Content string `json:"content"`
Status int `json:"status"`
} `json:"change"`
}
if err := json.Unmarshal([]byte(out), &got); err != nil || got.Change.Name != "shown change" || got.Change.Status != fakeglpi.StatusAssigned {
t.Errorf("json show = %q err %v", out, err)
}
}
func TestChangeTransition(t *testing.T) {
srv := boot(t)
id := srv.AddChange(fakeglpi.Change{Name: "flow", Status: fakeglpi.StatusNew, Urgency: 3, Impact: 3})
out, errb, code := run(t, "change", "transition", strconv.Itoa(id), "solved")
if code != 0 {
t.Fatalf("code = %d, stderr = %q", code, errb)
}
if !strings.Contains(out, strconv.Itoa(id)) {
t.Errorf("confirmation = %q", out)
}
if got, _ := srv.Change(id); got.Status != fakeglpi.StatusSolved {
t.Errorf("stored status = %d, want solved", got.Status)
}
out, errb, code = run(t, "change", "transition", strconv.Itoa(id), strconv.Itoa(fakeglpi.StatusClosed))
if code != 0 {
t.Fatalf("numeric transition code = %d, stderr = %q", code, errb)
}
if got, _ := srv.Change(id); got.Status != fakeglpi.StatusClosed {
t.Errorf("stored status = %d, want closed", got.Status)
}
}
func TestChangeFollowup(t *testing.T) {
srv := boot(t)
id := srv.AddChange(fakeglpi.Change{Name: "with note", Status: fakeglpi.StatusNew, Urgency: 3, Impact: 3})
content := contentFile(t, "REPORT delivered: see inbox")
out, errb, code := run(t, "change", "followup", strconv.Itoa(id), "--content", content)
if code != 0 {
t.Fatalf("code = %d, stderr = %q", code, errb)
}
if !strings.Contains(out, strconv.Itoa(id)) {
t.Errorf("confirmation = %q", out)
}
fups := srv.Followups(id)
if len(fups) != 1 || fups[0].Content != "REPORT delivered: see inbox" {
t.Errorf("followups = %+v", fups)
}
empty := contentFile(t, "")
_, errb, code = run(t, "change", "followup", strconv.Itoa(id), "--content", empty)
if code != 1 || !strings.Contains(errb, "content") {
t.Errorf("empty followup = code %d stderr %q, want usage error", code, errb)
}
}
func TestCISearchAndShow(t *testing.T) {
srv := boot(t)
web := srv.AddItem("Computer", map[string]any{"name": "web-01", "serial": "ABC123"})
out, errb, code := run(t, "ci", "search", "Computer", "web")
if code != 0 {
t.Fatalf("code = %d, stderr = %q", code, errb)
}
if !strings.Contains(out, "web-01") || !strings.Contains(out, strconv.Itoa(web)) {
t.Errorf("search = %q", out)
}
out, _, code = run(t, "ci", "search", "Computer", "web", "-o", "json")
if code != 0 {
t.Fatalf("json search code %d", code)
}
var arr struct {
Results []struct {
ID int `json:"id"`
Name string `json:"name"`
} `json:"results"`
}
if err := json.Unmarshal([]byte(out), &arr); err != nil || len(arr.Results) != 1 || arr.Results[0].Name != "web-01" {
t.Errorf("json search = %q err %v", out, err)
}
out, _, code = run(t, "ci", "show", "Computer", strconv.Itoa(web), "-o", "json")
if code != 0 {
t.Fatalf("ci show code = %d", code)
}
var raw map[string]any
if err := json.Unmarshal([]byte(out), &raw); err != nil || raw["serial"] != "ABC123" {
t.Errorf("ci show = %q err %v", out, err)
}
if _, errb, code := run(t, "ci", "show", "Computer", "424242"); code != 2 || !strings.Contains(errb, "http 404") {
t.Errorf("missing ci = code %d stderr %q, want exit 2 http 404", code, errb)
}
}
// THE agent-mode CLI proof: the fake rejects change creation unless the
// session's active profile is 5; --profile and MGLPI_PROFILE_ID both
// must flip it.
func TestProfileSwitchAgentMode(t *testing.T) {
tests := []struct {
name string
envProfile string
flag []string
wantCode int
}{
{"no profile -> rejected", "", nil, 2},
{"--profile 5 -> accepted", "", []string{"--profile", "5"}, 0},
{"--profile 4 -> rejected", "", []string{"--profile", "4"}, 2},
{"env profile 5 -> accepted", "5", nil, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
srv := boot(t)
srv.RequireChangeProfile = 5
t.Setenv("MGLPI_PROFILE_ID", tt.envProfile)
args := append([]string{"change", "create", "--title", "agent-mode", "--content", "-"}, tt.flag...)
out, errb, code := run(t, args...)
if code != tt.wantCode {
t.Fatalf("code = %d (stderr %q), want %d", code, errb, tt.wantCode)
}
if tt.wantCode == 0 {
if !strings.Contains(out, "created change #") {
t.Errorf("out = %q", out)
}
} else if !strings.Contains(errb, "http 403") {
t.Errorf("stderr = %q, want http 403", errb)
}
})
}
}
func TestAPIErrorIsExitTwo(t *testing.T) {
srv := boot(t)
srv.Fail = &fakeglpi.FailSpec{Status: 404, Body: `[{"ERROR_ITEM_NOT_FOUND":"gone %s"}]`}
out, errb, code := run(t, "change", "list")
if code != 2 {
t.Fatalf("code = %d, want 2", code)
}
if out != "" {
t.Errorf("stdout on API error: %q", out)
}
lines := strings.Split(strings.TrimRight(errb, "\n"), "\n")
if len(lines) != 1 || !strings.Contains(lines[0], "http 404") {
t.Fatalf("stderr = %q, want single parseable line with http 404", errb)
}
}
func TestTokensNeverPrinted(t *testing.T) {
srv := fakeglpi.New(testApp, testUser)
t.Cleanup(srv.Close)
t.Setenv("MGLPI_URL", srv.URL)
t.Setenv("MGLPI_APP_TOKEN", "wrong-app-token")
t.Setenv("MGLPI_USER_TOKEN", testUser)
t.Setenv("MGLPI_PROFILE_ID", "")
_, errb, code := run(t, "change", "list")
if code != 2 {
t.Fatalf("code = %d, want 2", code)
}
if strings.Contains(errb, "wrong-app-token") || strings.Contains(errb, testUser) || strings.Contains(errb, testApp) {
t.Fatalf("stderr leaks a token: %q", errb)
}
if strings.Count(errb, "\n") != 1 { // one diagnostic line + trailing newline
t.Fatalf("stderr not one line: %q", errb)
}
}
func TestHelpExitsZero(t *testing.T) {
boot(t)
out, _, code := run(t, "help")
if code != 0 || !strings.Contains(out, "change") {
t.Fatalf("help code = %d out = %q", code, out)
}
}
+366
View File
@@ -0,0 +1,366 @@
package cli
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"sort"
"strconv"
"strings"
"git.knownelement.com/ukrrs/mopac-glpi-go/glpi"
)
func marshalIndent(v any) ([]byte, error) { return json.MarshalIndent(v, "", " ") }
// --- whoami -----------------------------------------------------------------
// cmdWhoami lists the session's profiles. It NEVER switches the active
// profile (agent mode's MGLPI_PROFILE_ID is deliberately not applied).
func cmdWhoami(args []string, stdout, stderr io.Writer) int {
fs, cfgPath, out := newFlags("whoami", stderr)
pos, err := parseArgs(fs, args)
if err != nil || len(pos) != 0 {
return usageErr(stderr, "whoami: usage: mglpi whoami")
}
c, _, err := client(*cfgPath, 0)
if err != nil {
return usageErr(stderr, "%v", err)
}
profs, err := c.GetMyProfiles(context.Background())
if err != nil {
return apiErr(stderr, err)
}
if *out == "json" {
emitJSON(stdout, map[string]any{"profiles": profs})
return 0
}
for _, p := range profs {
line := fmt.Sprintf("%-6d %s", p.ID, p.Name)
if p.IsActive {
line += " [active]"
}
fmt.Fprintln(stdout, line)
}
return 0
}
// --- change -------------------------------------------------------------------
func cmdChange(args []string, stdout, stderr io.Writer) int {
if len(args) == 0 {
return usageErr(stderr, "change: expected list|show|create|transition|followup (see mglpi help)")
}
sub, rest := args[0], args[1:]
switch sub {
case "list":
return cmdChangeList(rest, stdout, stderr)
case "show":
return cmdChangeShow(rest, stdout, stderr)
case "create":
return cmdChangeCreate(rest, stdout, stderr)
case "transition":
return cmdChangeTransition(rest, stdout, stderr)
case "followup":
return cmdChangeFollowup(rest, stdout, stderr)
default:
return usageErr(stderr, "change: unknown subcommand %q", sub)
}
}
// withClient is the common preamble: resolve config + profile, switch
// profile when one is set (an API op -> exit 2 on failure), and hand
// the client over.
func withClient(stderr io.Writer, cfgPath string, profileFlag int, fn func(c *glpi.Client, ctx context.Context) int) int {
c, profile, err := client(cfgPath, profileFlag)
if err != nil {
return usageErr(stderr, "%v", err)
}
ctx := context.Background()
if profile > 0 {
if err := c.ChangeActiveProfile(ctx, profile); err != nil {
return apiErr(stderr, err)
}
}
return fn(c, ctx)
}
func cmdChangeList(args []string, stdout, stderr io.Writer) int {
fs, cfgPath, out := newFlags("change list", stderr)
status := fs.String("status", "", "filter by status name or numeric id (e.g. new, solved, 1)")
pos, err := parseArgs(fs, args)
if err != nil || len(pos) != 0 {
return usageErr(stderr, "change list: usage: mglpi change list [--status N|NAME]")
}
want := 0
if *status != "" {
if id, ok := glpi.StatusID(*status); ok {
want = id
} else {
n, err := strconv.Atoi(*status)
if err != nil || n <= 0 {
return usageErr(stderr, "change list: --status must be a status name or positive number, got %q", *status)
}
want = n
}
}
return withClient(stderr, *cfgPath, 0, func(c *glpi.Client, ctx context.Context) int {
rows, err := c.ListChanges(ctx, want)
if err != nil {
return apiErr(stderr, err)
}
if *out == "json" {
emitJSON(stdout, map[string]any{"changes": rows})
return 0
}
for _, r := range rows {
fmt.Fprintf(stdout, "%-6d %-12s %s\n", r.ID, glpi.StatusName(r.Status), r.Name)
}
return 0
})
}
func cmdChangeShow(args []string, stdout, stderr io.Writer) int {
fs, cfgPath, out := newFlags("change show", stderr)
pos, err := parseArgs(fs, args)
if err != nil || len(pos) != 1 {
return usageErr(stderr, "change show: usage: mglpi change show ID")
}
id, err := strconv.Atoi(pos[0])
if err != nil {
return usageErr(stderr, "change show: ID must be numeric, got %q", pos[0])
}
return withClient(stderr, *cfgPath, 0, func(c *glpi.Client, ctx context.Context) int {
ch, err := c.GetChange(ctx, id)
if err != nil {
return apiErr(stderr, err)
}
if *out == "json" {
emitJSON(stdout, map[string]any{"change": ch})
return 0
}
printChange(stdout, ch)
return 0
})
}
func printChange(w io.Writer, ch *glpi.Change) {
fmt.Fprintf(w, "#%d %s\n", ch.ID, ch.Name)
fmt.Fprintf(w, "Status: %-12s Urgency: %d Impact: %d\n", glpi.StatusName(ch.Status), ch.Urgency, ch.Impact)
fmt.Fprintf(w, "Created: %s Updated: %s\n", ch.Date, ch.DateMod)
if ch.Content != "" {
fmt.Fprintln(w)
fmt.Fprintln(w, ch.Content)
}
}
func cmdChangeCreate(args []string, stdout, stderr io.Writer) int {
fs, cfgPath, out := newFlags("change create", stderr)
title := fs.String("title", "", "change title (required)")
content := fs.String("content", "-", "content body from FILE, or - for stdin")
urgency := fs.Int("urgency", 3, "urgency 1..5 (3 = medium)")
impact := fs.Int("impact", 3, "impact 1..5 (3 = medium)")
profile := fs.Int("profile", 0, "agent profile id to switch to after InitSession (e.g. 5 = Hotliner)")
pos, err := parseArgs(fs, args)
if err != nil || len(pos) != 0 || *title == "" {
return usageErr(stderr, "change create: usage: mglpi change create --title T [--urgency N] [--impact N] [--profile N] [--content FILE|-]")
}
if *urgency < 1 || *urgency > 5 || *impact < 1 || *impact > 5 {
return usageErr(stderr, "change create: --urgency/--impact must be 1..5")
}
body := ""
if *content != "" {
text, err := readBody(*content)
if err != nil {
return usageErr(stderr, "%v", err)
}
body = text
}
return withClient(stderr, *cfgPath, *profile, func(c *glpi.Client, ctx context.Context) int {
id, err := c.CreateChange(ctx, *title, body, *urgency, *impact)
if err != nil {
return apiErr(stderr, err)
}
if *out == "json" {
emitJSON(stdout, map[string]any{"change": map[string]any{"id": id}})
return 0
}
fmt.Fprintf(stdout, "created change #%d\n", id)
return 0
})
}
func cmdChangeTransition(args []string, stdout, stderr io.Writer) int {
fs, cfgPath, out := newFlags("change transition", stderr)
pos, err := parseArgs(fs, args)
if err != nil || len(pos) != 2 {
return usageErr(stderr, "change transition: usage: mglpi change transition ID STATUS")
}
id, err := strconv.Atoi(pos[0])
if err != nil {
return usageErr(stderr, "change transition: ID must be numeric, got %q", pos[0])
}
status, ok := glpi.StatusID(pos[1])
if !ok {
status, err = strconv.Atoi(pos[1])
if err != nil || status <= 0 {
return usageErr(stderr, "change transition: STATUS must be a status name or positive number, got %q", pos[1])
}
}
return withClient(stderr, *cfgPath, 0, func(c *glpi.Client, ctx context.Context) int {
if err := c.TransitionChange(ctx, id, status); err != nil {
return apiErr(stderr, err)
}
if *out == "json" {
ch, err := c.GetChange(ctx, id)
if err != nil {
return apiErr(stderr, err)
}
emitJSON(stdout, map[string]any{"change": ch})
return 0
}
fmt.Fprintf(stdout, "updated change #%d (status %s)\n", id, glpi.StatusName(status))
return 0
})
}
func cmdChangeFollowup(args []string, stdout, stderr io.Writer) int {
fs, cfgPath, out := newFlags("change followup", stderr)
content := fs.String("content", "-", "followup body from FILE, or - for stdin")
profile := fs.Int("profile", 0, "agent profile id to switch to after InitSession")
pos, err := parseArgs(fs, args)
if err != nil || len(pos) != 1 {
return usageErr(stderr, "change followup: usage: mglpi change followup ID [--content FILE|-]")
}
id, err := strconv.Atoi(pos[0])
if err != nil {
return usageErr(stderr, "change followup: ID must be numeric, got %q", pos[0])
}
body := ""
if *content != "" {
text, err := readBody(*content)
if err != nil {
return usageErr(stderr, "%v", err)
}
body = text
}
if strings.TrimSpace(body) == "" {
return usageErr(stderr, "change followup: content is required (stdin or --content FILE)")
}
return withClient(stderr, *cfgPath, *profile, func(c *glpi.Client, ctx context.Context) int {
if err := c.AddFollowup(ctx, id, body); err != nil {
return apiErr(stderr, err)
}
if *out == "json" {
emitJSON(stdout, map[string]any{"followup": map[string]any{"items_id": id}})
return 0
}
fmt.Fprintf(stdout, "added followup to change #%d\n", id)
return 0
})
}
// readBody loads a body from a file, or from stdin when path is "-".
func readBody(path string) (string, error) {
if path == "-" {
b, err := io.ReadAll(os.Stdin)
if err != nil {
return "", fmt.Errorf("content: cannot read stdin: %w", err)
}
return string(b), nil
}
b, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("content: cannot read %s", path)
}
return string(b), nil
}
// --- ci ----------------------------------------------------------------------
func cmdCI(args []string, stdout, stderr io.Writer) int {
if len(args) == 0 {
return usageErr(stderr, "ci: expected search|show (see mglpi help)")
}
sub, rest := args[0], args[1:]
switch sub {
case "search":
return cmdCISearch(rest, stdout, stderr)
case "show":
return cmdCIShow(rest, stdout, stderr)
default:
return usageErr(stderr, "ci: unknown subcommand %q", sub)
}
}
func cmdCISearch(args []string, stdout, stderr io.Writer) int {
fs, cfgPath, out := newFlags("ci search", stderr)
pos, err := parseArgs(fs, args)
if err != nil || len(pos) != 2 {
return usageErr(stderr, "ci search: usage: mglpi ci search TYPE TERM")
}
return withClient(stderr, *cfgPath, 0, func(c *glpi.Client, ctx context.Context) int {
rows, err := c.SearchCI(ctx, pos[0], pos[1])
if err != nil {
return apiErr(stderr, err)
}
type result struct {
ID int `json:"id"`
Name string `json:"name"`
}
results := make([]result, 0, len(rows))
for _, r := range rows {
results = append(results, result{ID: r.ID, Name: r.Name})
}
if *out == "json" {
emitJSON(stdout, map[string]any{"results": results})
return 0
}
for _, r := range results {
fmt.Fprintf(stdout, "%-6d %s\n", r.ID, r.Name)
}
return 0
})
}
func cmdCIShow(args []string, stdout, stderr io.Writer) int {
fs, cfgPath, out := newFlags("ci show", stderr)
pos, err := parseArgs(fs, args)
if err != nil || len(pos) != 2 {
return usageErr(stderr, "ci show: usage: mglpi ci show TYPE ID")
}
id, err := strconv.Atoi(pos[1])
if err != nil {
return usageErr(stderr, "ci show: ID must be numeric, got %q", pos[1])
}
return withClient(stderr, *cfgPath, 0, func(c *glpi.Client, ctx context.Context) int {
obj, err := c.GetItem(ctx, pos[0], id)
if err != nil {
return apiErr(stderr, err)
}
if *out == "json" {
emitJSON(stdout, obj)
return 0
}
fmt.Fprintf(stdout, "%s #%d %s\n", pos[0], id, obj["name"])
for _, k := range sortedKeys(obj) {
if k == "id" || k == "name" {
continue
}
fmt.Fprintf(stdout, " %s: %v\n", k, obj[k])
}
return 0
})
}
// sortedKeys orders an object's keys for stable text output.
func sortedKeys(m map[string]any) []string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
+214
View File
@@ -0,0 +1,214 @@
// Package config loads GLPI connection settings for the mglpi CLI.
// The base URL, app token, and user token arrive ONLY from (a)
// MGLPI_URL / MGLPI_APP_TOKEN / MGLPI_USER_TOKEN environment variables
// or (b) a 0600 env file parsed in pure Go — never from flags or
// command-line arguments. MGLPI_PROFILE_ID is optional (agent mode: the
// CLI switches to this profile after InitSession). Files looser than
// 0600 are refused BEFORE being read. Error messages carry line numbers
// and key names, never values; tokens are never logged or echoed.
package config
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
)
// Keys understood in the environment and the env file.
const (
KeyURL = "MGLPI_URL"
KeyAppToken = "MGLPI_APP_TOKEN"
KeyUserToken = "MGLPI_USER_TOKEN"
KeyProfileID = "MGLPI_PROFILE_ID"
)
// Config is the resolved connection set.
type Config struct {
BaseURL string // full API endpoint, e.g. https://cmdb.knownelement.com/apirest.php
AppToken string // GLPI App-Token; header-only, never logged
UserToken string // GLPI user token; Authorization header at init, never logged
ProfileID int // optional agent profile id; 0 = no auto-switch
}
// Source records where each value came from (for safe diagnostics).
type Source struct{ Env, File string }
// Load resolves settings: process env wins over the env file. path may
// be empty (file simply not consulted). A file that exists but is looser
// than 0600 is an error before any read. MGLPI_URL, MGLPI_APP_TOKEN and
// MGLPI_USER_TOKEN are required; there is no default server.
func Load(path string) (*Config, *Source, error) {
cfg := &Config{}
src := &Source{}
fileVals, err := loadFile(path)
if err != nil {
return nil, nil, err
}
get := func(key string) (string, bool) {
if v, ok := os.LookupEnv(key); ok && v != "" {
src.Env = key
return v, true
}
if v, ok := fileVals[key]; ok && v != "" {
src.File = key
return v, true
}
return "", false
}
if v, ok := get(KeyURL); ok {
cfg.BaseURL = strings.TrimRight(v, "/")
}
if v, ok := get(KeyAppToken); ok {
cfg.AppToken = v
}
if v, ok := get(KeyUserToken); ok {
cfg.UserToken = v
}
// MGLPI_PROFILE_ID is optional (agent mode). Empty and unset are 0;
// a present but non-numeric value is an error that names the key and
// never echoes the value.
if v, ok := get(KeyProfileID); ok {
n, err := strconv.Atoi(v)
if err != nil {
return nil, nil, fmt.Errorf("config: %s: must be an integer", KeyProfileID)
}
cfg.ProfileID = n
}
var missing []string
if cfg.BaseURL == "" {
missing = append(missing, KeyURL)
}
if cfg.AppToken == "" {
missing = append(missing, KeyAppToken)
}
if cfg.UserToken == "" {
missing = append(missing, KeyUserToken)
}
if len(missing) > 0 {
return nil, nil, fmt.Errorf("config: missing %s (set env or %s)", strings.Join(missing, " and "), pathOrDefault(path))
}
return cfg, src, nil
}
// loadFile reads and parses path when given. It enforces the 0600 rule
// before reading a single byte; a missing file is not an error (env may
// carry everything).
func loadFile(path string) (map[string]string, error) {
if path == "" {
return nil, nil
}
info, err := os.Stat(path)
if os.IsNotExist(err) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("config: %s: %w", filepath.Base(path), err)
}
if info.Mode().Perm()&0o077 != 0 {
return nil, fmt.Errorf("config: %s: insecure mode %04o (must be 0600 or stricter)", filepath.Base(path), info.Mode().Perm())
}
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("config: %s: unreadable", filepath.Base(path))
}
vals, err := parseEnvFile(data)
if err != nil {
return nil, fmt.Errorf("config: %s: %w", filepath.Base(path), err)
}
return vals, nil
}
// parseEnvFile parses KEY=VALUE lines in pure Go (same discipline as
// mopac-bitwarden-go): no sourcing, no shell expansion, no interpolation.
// Comments, blank lines, an optional "export " prefix and one matched pair
// of surrounding quotes are handled; later duplicate keys win. Malformed
// lines fail with the line NUMBER only — never the contents.
func parseEnvFile(data []byte) (map[string]string, error) {
out := map[string]string{}
for i, line := range strings.Split(string(data), "\n") {
line = strings.TrimRight(line, "\r")
trimmed := strings.TrimSpace(line)
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
continue
}
line = trimmed
if strings.HasPrefix(line, "export ") || strings.HasPrefix(line, "export\t") {
line = strings.TrimSpace(line[len("export"):])
}
eq := strings.IndexByte(line, '=')
if eq <= 0 {
return nil, fmt.Errorf("line %d: malformed KEY=VALUE line", i+1)
}
key := strings.TrimSpace(line[:eq])
if !validEnvKey(key) {
return nil, fmt.Errorf("line %d: malformed KEY=VALUE line", i+1)
}
value := strings.TrimSpace(line[eq+1:])
if idx := commentIndex(value); idx >= 0 {
value = strings.TrimSpace(value[:idx])
}
out[key] = unquote(value)
}
return out, nil
}
func validEnvKey(key string) bool {
if key == "" {
return false
}
for i := 0; i < len(key); i++ {
c := key[i]
switch {
case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c == '_':
case c >= '0' && c <= '9':
if i == 0 {
return false
}
default:
return false
}
}
return true
}
// commentIndex finds an inline comment start (a # preceded by whitespace)
// outside a quoted value; -1 if none.
func commentIndex(value string) int {
var quote byte
for i := 0; i < len(value); i++ {
c := value[i]
switch {
case quote != 0:
if c == quote {
quote = 0
}
case c == '"' || c == '\'':
quote = c
case c == '#' && (i == 0 || value[i-1] == ' ' || value[i-1] == ' '):
return i
}
}
return -1
}
func unquote(v string) string {
if len(v) >= 2 {
if (v[0] == '"' && v[len(v)-1] == '"') || (v[0] == '\'' && v[len(v)-1] == '\'') {
return v[1 : len(v)-1]
}
}
return v
}
func pathOrDefault(path string) string {
if path != "" {
return path
}
return "the --config env file"
}
+145
View File
@@ -0,0 +1,145 @@
package config
import (
"os"
"path/filepath"
"strings"
"testing"
)
func writeFile(t *testing.T, name string, mode os.FileMode, content string) string {
t.Helper()
path := filepath.Join(t.TempDir(), name)
if err := os.WriteFile(path, []byte(content), mode); err != nil {
t.Fatal(err)
}
return path
}
func TestLoadEnvOnly(t *testing.T) {
t.Setenv("MGLPI_URL", "https://cmdb.example/apirest.php/")
t.Setenv("MGLPI_APP_TOKEN", "a1")
t.Setenv("MGLPI_USER_TOKEN", "u1")
cfg, src, err := Load("")
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.BaseURL != "https://cmdb.example/apirest.php" {
t.Errorf("BaseURL = %q, want trailing slash trimmed", cfg.BaseURL)
}
if cfg.AppToken != "a1" || cfg.UserToken != "u1" {
t.Errorf("tokens = %q/%q", cfg.AppToken, cfg.UserToken)
}
if cfg.ProfileID != 0 {
t.Errorf("ProfileID = %d, want 0 when unset", cfg.ProfileID)
}
if src.Env == "" {
t.Errorf("source env = %q, want a key name", src.Env)
}
}
func TestLoadFileOnly(t *testing.T) {
path := writeFile(t, "env", 0o600,
"MGLPI_URL=https://cmdb.example/apirest.php\nMGLPI_APP_TOKEN=a2\nMGLPI_USER_TOKEN=u2\nMGLPI_PROFILE_ID=5\n")
cfg, _, err := Load(path)
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.BaseURL != "https://cmdb.example/apirest.php" || cfg.AppToken != "a2" || cfg.UserToken != "u2" {
t.Errorf("cfg = %+v", cfg)
}
if cfg.ProfileID != 5 {
t.Errorf("ProfileID = %d, want 5", cfg.ProfileID)
}
}
func TestLoadEnvWinsOverFile(t *testing.T) {
t.Setenv("MGLPI_USER_TOKEN", "env-user")
path := writeFile(t, "env", 0o600, "MGLPI_URL=https://cmdb.example/apirest.php\nMGLPI_APP_TOKEN=fa\nMGLPI_USER_TOKEN=file-user\n")
cfg, src, err := Load(path)
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.UserToken != "env-user" {
t.Errorf("UserToken = %q, want env value to win", cfg.UserToken)
}
if src.File != "" && src.Env != "MGLPI_USER_TOKEN" {
t.Errorf("source = %+v", src)
}
}
func TestLoadRejectsLooseFile(t *testing.T) {
path := writeFile(t, "env", 0o644, "MGLPI_URL=https://cmdb.example/apirest.php\nMGLPI_APP_TOKEN=a\nMGLPI_USER_TOKEN=u\n")
_, _, err := Load(path)
if err == nil || !strings.Contains(err.Error(), "insecure mode") {
t.Fatalf("err = %v, want insecure-mode rejection", err)
}
}
func TestLoadMissingEverything(t *testing.T) {
_, _, err := Load(filepath.Join(t.TempDir(), "absent"))
if err == nil || !strings.Contains(err.Error(), "MGLPI_URL") {
t.Fatalf("err = %v, want guidance naming MGLPI_URL", err)
}
}
func TestLoadTokenAbsent(t *testing.T) {
t.Setenv("MGLPI_URL", "https://cmdb.example/apirest.php")
t.Setenv("MGLPI_APP_TOKEN", "a")
path := writeFile(t, "env", 0o600, "# nothing useful\n")
_, _, err := Load(path)
if err == nil || !strings.Contains(err.Error(), "MGLPI_USER_TOKEN") {
t.Fatalf("err = %v, want MGLPI_USER_TOKEN named", err)
}
}
func TestLoadMalformedLineReportsNumberOnly(t *testing.T) {
path := writeFile(t, "env", 0o600,
"MGLPI_URL=https://cmdb.example/apirest.php\nMGLPI_APP_TOKEN=secret-app\nMGLPI_USER_TOKEN=secret-user\nBROKEN LINE HERE\n")
_, _, err := Load(path)
if err == nil || !strings.Contains(err.Error(), "line 4") {
t.Fatalf("err = %v, want line-number-only diagnostic", err)
}
if err != nil && (strings.Contains(err.Error(), "secret-app") || strings.Contains(err.Error(), "secret-user")) {
t.Fatalf("err = %v leaks file contents", err)
}
}
func TestLoadQuotedAndExported(t *testing.T) {
path := writeFile(t, "env", 0o600,
"export MGLPI_URL=\"https://cmdb.example/apirest.php\"\nexport MGLPI_APP_TOKEN='a3'\nexport MGLPI_USER_TOKEN=u3\n")
cfg, _, err := Load(path)
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.BaseURL != "https://cmdb.example/apirest.php" || cfg.AppToken != "a3" || cfg.UserToken != "u3" {
t.Errorf("cfg = %+v, want quotes stripped", cfg)
}
}
func TestProfileIDValidation(t *testing.T) {
t.Run("absent is 0", func(t *testing.T) {
path := writeFile(t, "env", 0o600, "MGLPI_URL=https://cmdb.example/apirest.php\nMGLPI_APP_TOKEN=a\nMGLPI_USER_TOKEN=u\n")
cfg, _, err := Load(path)
if err != nil || cfg.ProfileID != 0 {
t.Fatalf("cfg = %+v err = %v", cfg, err)
}
})
t.Run("empty string is 0", func(t *testing.T) {
path := writeFile(t, "env", 0o600, "MGLPI_URL=https://cmdb.example/apirest.php\nMGLPI_APP_TOKEN=a\nMGLPI_USER_TOKEN=u\nMGLPI_PROFILE_ID=\n")
cfg, _, err := Load(path)
if err != nil || cfg.ProfileID != 0 {
t.Fatalf("cfg = %+v err = %v", cfg, err)
}
})
t.Run("garbage is an error that never echoes the value", func(t *testing.T) {
path := writeFile(t, "env", 0o600, "MGLPI_URL=https://cmdb.example/apirest.php\nMGLPI_APP_TOKEN=a\nMGLPI_USER_TOKEN=u\nMGLPI_PROFILE_ID=hotliner\n")
_, _, err := Load(path)
if err == nil || !strings.Contains(err.Error(), "MGLPI_PROFILE_ID") {
t.Fatalf("err = %v, want MGLPI_PROFILE_ID named", err)
}
if strings.Contains(err.Error(), "hotliner") {
t.Fatalf("err = %v echoes the value", err)
}
})
}
+718
View File
@@ -0,0 +1,718 @@
// Package fakeglpi is a stateful in-memory GLPI REST fake used by the
// test suite and the smoke run. The real CMDB is NEVER contacted.
// It implements exactly the endpoints the glpi client uses, enforces
// App-Token + session auth on every one of them, and records every
// request (headers included) so tests can assert the header discipline.
//
// GLPI quirks modeled faithfully:
// - POST create endpoints return an ARRAY: [{"id":N,"message":"..."}].
// - Change create takes {"input":{...}} (object); ITILFollowup REQUIRES
// {"input":[{...}]} (array of objects) and rejects the object form.
// - search endpoints return data rows OBJECTS KEYED BY FIELD-ID STRING
// ({"1":"name","2":7,"12":3}) when forcedisplay is used.
// - initSession -> {"session_token":"..."}; killSession invalidates it.
// - changeActiveProfile switches the session's active profile; with
// RequireChangeProfile set, change creation is rejected (403
// ERROR_RIGHT_MISSING) until the right profile is active.
//
// Error responses deliberately echo the presented token back in the
// body: any test that survives that proves the client never surfaces
// response bodies (token-redaction guarantee).
package fakeglpi
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"sort"
"strconv"
"strings"
"sync"
)
// criteria is one search criterion from the criteria query parameter.
type criteria struct {
Field int `json:"field"`
Searchtype string `json:"searchtype"`
Value any `json:"value"`
}
// Change status constants (GLPI change lifecycle).
const (
StatusNew = 1
StatusEvaluation = 2
StatusApproval = 3
StatusTest = 4
StatusQualification = 5
StatusWaiting = 6
StatusAccepted = 7
StatusAssigned = 8
StatusPlanned = 9
StatusPending = 10
StatusSolved = 11
StatusClosed = 12
)
// Request is one recorded exchange (auth checked, body captured).
type Request struct {
Method string
Path string // path without query, trailing slash normalized
Query string // raw query
Body string
// What was presented in each auth header (header-discipline tests).
AppToken string
AuthHeader string // Authorization header (initSession only)
SessionToken string // Session-Token header (everything after init)
}
// FailSpec pins the next response (error-mapping tests). The body is a
// format string: %s is replaced with the token presented on the request.
type FailSpec struct {
Status int
Body string
}
// Profile is one GLPI profile of the logged-in user.
type Profile struct {
ID int `json:"id"`
Name string `json:"name"`
IsActive bool `json:"is_active"`
}
// Change is the stored change (server side).
type Change struct {
ID int `json:"id"`
Name string `json:"name"`
Content string `json:"content"`
Status int `json:"status"`
Urgency int `json:"urgency"`
Impact int `json:"impact"`
Date string `json:"date"`
DateMod string `json:"date_mod"`
}
// Followup is one ITILFollowup attached to a change.
type Followup struct {
ID int `json:"id"`
Itemtype string `json:"itemtype"`
ItemsID int `json:"items_id"`
Content string `json:"content"`
Date string `json:"date"`
}
// Server is the fake GLPI.
type Server struct {
URL string
AppToken string
UserToken string
// RequireChangeProfile, when > 0, makes change creation answer 403
// ERROR_RIGHT_MISSING unless the session's active profile equals it
// (the agent-mode switch path).
RequireChangeProfile int
// Fail, when non-nil, is returned instead of normal handling; it is
// consumed by the first request that sees it.
Fail *FailSpec
mu sync.Mutex
srv *httptest.Server
requests []Request
sessions map[string]bool
activeProfile map[string]int
nextSess int
profiles []Profile
changes map[int]*Change
followups map[int][]Followup
items map[string]map[int]map[string]any
nextID int
}
// New starts a fake on a random port with GLPI's default profiles and a
// few demo CIs (Computers/Monitors) for search.
func New(appToken, userToken string) *Server {
s := newServer(appToken, userToken)
mux := http.NewServeMux()
mux.HandleFunc("/", s.handler)
s.srv = httptest.NewServer(mux)
s.URL = s.srv.URL
return s
}
// ListenAndServe runs the fake on a fixed address (the smoke run boots
// it in a container). requireChangeProfile sets the agent-mode gate.
func ListenAndServe(addr, appToken, userToken string, requireChangeProfile int) error {
s := newServer(appToken, userToken)
s.RequireChangeProfile = requireChangeProfile
seedDemo(s)
mux := http.NewServeMux()
mux.HandleFunc("/", s.handler)
return http.ListenAndServe(addr, mux)
}
func newServer(appToken, userToken string) *Server {
return &Server{
AppToken: appToken,
UserToken: userToken,
sessions: map[string]bool{},
activeProfile: map[string]int{},
profiles: []Profile{
{ID: 4, Name: "Self-Service"},
{ID: 5, Name: "Hotliner"},
{ID: 6, Name: "Super-admin", IsActive: true},
},
changes: map[int]*Change{},
followups: map[int][]Followup{},
items: map[string]map[int]map[string]any{},
nextID: 100,
}
}
// seedDemo adds the CIs the smoke run searches for.
func seedDemo(s *Server) {
s.AddItem("Computer", map[string]any{"name": "smoke-web-01", "serial": "SMOKEWEB01"})
s.AddItem("Computer", map[string]any{"name": "smoke-db-01", "serial": "SMOKEDB01"})
s.AddItem("Monitor", map[string]any{"name": "smoke-mon-01"})
}
// Close shuts the fake down.
func (s *Server) Close() { s.srv.Close() }
// Requests returns a copy of the recorded exchanges.
func (s *Server) Requests() []Request {
s.mu.Lock()
defer s.mu.Unlock()
out := make([]Request, len(s.requests))
copy(out, s.requests)
return out
}
// Sessions returns the still-valid session tokens (sorted).
func (s *Server) Sessions() []string {
s.mu.Lock()
defer s.mu.Unlock()
out := make([]string, 0, len(s.sessions))
for tok := range s.sessions {
out = append(out, tok)
}
sort.Strings(out)
return out
}
// SessionCount reports the number of valid sessions.
func (s *Server) SessionCount() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.sessions)
}
// AddChange seeds a change directly (bypassing REST) and returns its id.
func (s *Server) AddChange(c Change) int {
s.mu.Lock()
defer s.mu.Unlock()
s.nextID++
c.ID = s.nextID
if c.Status == 0 {
c.Status = StatusNew
}
if c.Date == "" {
c.Date = "2026-09-03T12:00:00Z"
}
if c.DateMod == "" {
c.DateMod = c.Date
}
cc := c
s.changes[c.ID] = &cc
return c.ID
}
// Change returns a copy of a stored change (for assertions).
func (s *Server) Change(id int) (Change, bool) {
s.mu.Lock()
defer s.mu.Unlock()
c, ok := s.changes[id]
if !ok {
return Change{}, false
}
return *c, true
}
// Followups returns the followups attached to a change (for assertions).
func (s *Server) Followups(changeID int) []Followup {
s.mu.Lock()
defer s.mu.Unlock()
out := make([]Followup, len(s.followups[changeID]))
copy(out, s.followups[changeID])
return out
}
// AddItem seeds a CI (any itemtype) directly and returns its id.
func (s *Server) AddItem(itemtype string, obj map[string]any) int {
s.mu.Lock()
defer s.mu.Unlock()
s.nextID++
id := s.nextID
obj["id"] = id
if s.items[itemtype] == nil {
s.items[itemtype] = map[int]map[string]any{}
}
s.items[itemtype][id] = obj
return id
}
// Item returns a copy of a stored CI (for assertions).
func (s *Server) Item(itemtype string, id int) (map[string]any, bool) {
s.mu.Lock()
defer s.mu.Unlock()
obj, ok := s.items[itemtype][id]
if !ok {
return nil, false
}
out := map[string]any{}
for k, v := range obj {
out[k] = v
}
return out, true
}
// presented picks the token the request showed (the one an echo may
// leak into an error body).
func presented(r *http.Request) string {
if v := r.Header.Get("Session-Token"); v != "" {
return v
}
if v := r.Header.Get("Authorization"); v != "" {
return v
}
return r.Header.Get("App-Token")
}
func (s *Server) handler(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
present := presented(r)
s.mu.Lock()
// Fail overrides everything (echoes the presented token in the body).
if s.Fail != nil {
spec := *s.Fail
s.Fail = nil
s.record(r, body)
s.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(spec.Status)
fmt.Fprintf(w, spec.Body, present)
return
}
// App-Token is required on EVERY endpoint.
if r.Header.Get("App-Token") != s.AppToken {
s.record(r, nil)
s.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `[{"ERROR_APP_TOKEN_PARAMETERS_MISSING":"presented %s"}]`, present)
return
}
// GLPI serves every endpoint under /apirest.php; accept both the
// prefixed and bare forms.
path := strings.TrimSuffix(r.URL.Path, "/")
path = strings.TrimPrefix(path, "/apirest.php")
if path == "" {
path = "/"
}
// initSession is the only endpoint that authenticates with the user
// token (Authorization: user_token ...); everything else needs a
// live Session-Token.
if path == "/initSession" {
respStatus, respBody := s.initSession(r)
s.record(r, body)
s.mu.Unlock()
writeJSON(w, respStatus, respBody)
return
}
tok := r.Header.Get("Session-Token")
if !s.sessions[tok] {
s.record(r, nil)
s.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, `[{"ERROR_SESSION_TOKEN_MISSING":"presented %s"}]`, present)
return
}
var (
respStatus = http.StatusOK
respBody string
)
q := r.URL.Query()
switch {
case (r.Method == http.MethodGet || r.Method == http.MethodPost) && path == "/killSession":
delete(s.sessions, tok)
delete(s.activeProfile, tok)
respBody = `true`
case r.Method == http.MethodGet && path == "/getMyProfiles":
respStatus, respBody = s.getMyProfiles(tok)
case r.Method == http.MethodPost && path == "/changeActiveProfile":
respStatus, respBody = s.changeActiveProfile(tok, body)
case r.Method == http.MethodGet && strings.HasPrefix(path, "/Profile/"):
respStatus, respBody = s.getProfile(tok, trimPrefixInt(path, "/Profile/"))
case r.Method == http.MethodPost && path == "/change":
respStatus, respBody = s.createChange(tok, body)
case r.Method == http.MethodGet && strings.HasPrefix(path, "/change/"):
respStatus, respBody = s.getChange(trimPrefixInt(path, "/change/"))
case r.Method == http.MethodPut && strings.HasPrefix(path, "/change/"):
respStatus, respBody = s.updateChange(tok, trimPrefixInt(path, "/change/"), body)
case r.Method == http.MethodPost && path == "/ITILFollowup":
respStatus, respBody = s.createFollowup(body)
case r.Method == http.MethodGet && strings.HasPrefix(path, "/search/"):
respStatus, respBody = s.search(itemtypeOf(path), q)
case len(strings.SplitN(strings.TrimPrefix(path, "/"), "/", 2)) == 2:
respStatus, respBody = s.getItem(path)
default:
respStatus, respBody = http.StatusNotFound, `[{"ERROR_ITEM_NOT_FOUND":true}]`
}
s.record(r, body)
s.mu.Unlock()
writeJSON(w, respStatus, respBody)
}
func writeJSON(w http.ResponseWriter, status int, body string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if body != "" {
io.WriteString(w, body)
}
}
// record appends one exchange; callers hold s.mu.
func (s *Server) record(r *http.Request, body []byte) {
s.requests = append(s.requests, Request{
Method: r.Method,
Path: strings.TrimSuffix(r.URL.Path, "/"),
Query: r.URL.RawQuery,
Body: string(body),
AppToken: r.Header.Get("App-Token"),
AuthHeader: r.Header.Get("Authorization"),
SessionToken: r.Header.Get("Session-Token"),
})
}
func (s *Server) initSession(r *http.Request) (int, string) {
if auth := r.Header.Get("Authorization"); auth != "user_token "+s.UserToken {
return http.StatusBadRequest, fmt.Sprintf(`[{"ERROR_GLPI_LOGIN":"login %s refused"}]`, auth)
}
s.nextSess++
tok := fmt.Sprintf("sess-%d", s.nextSess)
s.sessions[tok] = true
s.activeProfile[tok] = 6 // Super-admin is the default active profile
return http.StatusOK, `{"session_token":"` + tok + `"}`
}
func (s *Server) getMyProfiles(tok string) (int, string) {
out := make([]Profile, len(s.profiles))
copy(out, s.profiles)
for i := range out {
out[i].IsActive = out[i].ID == s.activeProfile[tok]
}
return jsonReply(out)
}
func (s *Server) changeActiveProfile(tok string, body []byte) (int, string) {
var p struct {
ProfilesID int `json:"profiles_id"`
}
if err := json.Unmarshal(body, &p); err != nil || p.ProfilesID == 0 {
return http.StatusBadRequest, `[{"ERROR_ARGUMENTS":true}]`
}
found := false
for _, pr := range s.profiles {
if pr.ID == p.ProfilesID {
found = true
}
}
if !found {
return http.StatusBadRequest, `[{"ERROR_PROFILE_NOT_FOUND":true}]`
}
s.activeProfile[tok] = p.ProfilesID
return http.StatusOK, `true`
}
func (s *Server) getProfile(tok string, id int) (int, string) {
for _, pr := range s.profiles {
if pr.ID == id {
p := pr
p.IsActive = p.ID == s.activeProfile[tok]
return jsonReply(p)
}
}
return http.StatusNotFound, `[{"ERROR_ITEM_NOT_FOUND":true}]`
}
// createChange enforces the agent profile gate, the object-input
// contract, and GLPI's array reply shape.
func (s *Server) createChange(tok string, body []byte) (int, string) {
if s.RequireChangeProfile > 0 && s.activeProfile[tok] != s.RequireChangeProfile {
return http.StatusForbidden, `[{"ERROR_RIGHT_MISSING":true}]`
}
input, ok := inputObject(body)
if !ok {
return http.StatusBadRequest, `[{"ERROR_INPUT_OBJECT_EXPECTED":true}]`
}
var c Change
if err := json.Unmarshal(input, &c); err != nil {
return http.StatusBadRequest, `[{"ERROR_ARGUMENTS":true}]`
}
if c.Name == "" {
return http.StatusBadRequest, `[{"ERROR_GLPI_ADD":true}]`
}
s.nextID++
c.ID = s.nextID
if c.Status == 0 {
c.Status = StatusNew
}
c.Date = "2026-09-03T12:00:00Z"
c.DateMod = c.Date
cc := c
s.changes[c.ID] = &cc
return http.StatusCreated, fmt.Sprintf(`[{"id":%d,"message":"change created"}]`, c.ID)
}
func (s *Server) getChange(id int) (int, string) {
c, ok := s.changes[id]
if !ok {
return http.StatusNotFound, `[{"ERROR_ITEM_NOT_FOUND":true}]`
}
return jsonReply(*c)
}
// updateChange applies a partial update and answers GLPI's array shape
// [{"<id>":true,"message":""}].
func (s *Server) updateChange(tok string, id int, body []byte) (int, string) {
if s.RequireChangeProfile > 0 && s.activeProfile[tok] != s.RequireChangeProfile {
return http.StatusForbidden, `[{"ERROR_RIGHT_MISSING":true}]`
}
c, ok := s.changes[id]
if !ok {
return http.StatusNotFound, `[{"ERROR_ITEM_NOT_FOUND":true}]`
}
input, ok := inputObject(body)
if !ok {
return http.StatusBadRequest, `[{"ERROR_INPUT_OBJECT_EXPECTED":true}]`
}
var p Change
if err := json.Unmarshal(input, &p); err != nil {
return http.StatusBadRequest, `[{"ERROR_ARGUMENTS":true}]`
}
if p.Name != "" {
c.Name = p.Name
}
if p.Content != "" {
c.Content = p.Content
}
if p.Status != 0 {
if p.Status < StatusNew || p.Status > StatusClosed {
return http.StatusBadRequest, `[{"ERROR_GLPI_UPDATE":true}]`
}
c.Status = p.Status
}
if p.Urgency != 0 {
c.Urgency = p.Urgency
}
if p.Impact != 0 {
c.Impact = p.Impact
}
c.DateMod = "2026-09-03T13:00:00Z"
return http.StatusOK, fmt.Sprintf(`[{"%d":true,"message":""}]`, id)
}
// createFollowup enforces the ARRAY-input contract ({"input":[{...}]});
// the object form is rejected, mirroring the real ITILFollowup endpoint.
func (s *Server) createFollowup(body []byte) (int, string) {
var probe struct {
Input json.RawMessage `json:"input"`
}
if err := json.Unmarshal(body, &probe); err != nil || len(probe.Input) == 0 {
return http.StatusBadRequest, `[{"ERROR_ARGUMENTS":true}]`
}
if bytes.TrimSpace(probe.Input)[0] != '[' {
return http.StatusBadRequest, `[{"ERROR_INPUT_ARRAY_EXPECTED":true}]`
}
var ins []Followup
if err := json.Unmarshal(probe.Input, &ins); err != nil {
return http.StatusBadRequest, `[{"ERROR_ARGUMENTS":true}]`
}
var created []map[string]any
for _, in := range ins {
if in.Itemtype != "Change" || in.Content == "" {
return http.StatusBadRequest, `[{"ERROR_GLPI_ADD":true}]`
}
if _, ok := s.changes[in.ItemsID]; !ok {
return http.StatusBadRequest, `[{"ERROR_GLPI_ADD":true}]`
}
s.nextID++
in.ID = s.nextID
in.Date = "2026-09-03T13:00:00Z"
s.followups[in.ItemsID] = append(s.followups[in.ItemsID], in)
created = append(created, map[string]any{"id": in.ID, "message": "followup added"})
}
if created == nil {
created = []map[string]any{}
}
// Create endpoints answer 201 with the array reply shape.
return http.StatusCreated, mustJSON(created)
}
func mustJSON(v any) string {
b, err := json.Marshal(v)
if err != nil {
panic(err)
}
return string(b)
}
// search serves /search/<itemtype>: criteria filtering plus rows keyed
// by forcedisplay field-id strings ({"1":"name","2":7,"12":3}).
func (s *Server) search(itemtype string, q url.Values) (int, string) {
if itemtype != "Change" && s.items[itemtype] == nil {
return http.StatusBadRequest, `[{"ERROR_GLPI_SEARCH":true}]`
}
base := map[int]map[string]any{}
var ids []int
appendRow := func(id int, row map[string]any) {
base[id] = row
ids = append(ids, id)
}
if itemtype == "Change" {
for id, c := range s.changes {
appendRow(id, map[string]any{"1": c.Name, "2": c.ID, "12": c.Status})
}
} else {
for id, obj := range s.items[itemtype] {
name, _ := obj["name"].(string)
appendRow(id, map[string]any{"1": name, "2": id})
}
}
sort.Ints(ids)
var criteriaList []criteria
if c := q.Get("criteria"); c != "" {
if err := json.Unmarshal([]byte(c), &criteriaList); err != nil {
return http.StatusBadRequest, `[{"ERROR_GLPI_SEARCH":true}]`
}
}
rows := []map[string]any{}
for _, id := range ids {
row := base[id]
if !matchCriteria(row, criteriaList) {
continue
}
forced := q["forcedisplay[]"]
if len(forced) == 0 {
forced = []string{"1", "2"}
}
projected := map[string]any{}
for _, f := range forced {
if v, ok := row[f]; ok {
projected[f] = v
}
}
rows = append(rows, projected)
}
out := map[string]any{
"totalcount": len(rows),
"count": len(rows),
"sort": 1,
"order": "ASC",
"data": rows,
}
return jsonReply(out)
}
func matchCriteria(row map[string]any, criteriaList []criteria) bool {
for _, cr := range criteriaList {
val, ok := row[strconv.Itoa(cr.Field)]
if !ok {
return false
}
switch cr.Searchtype {
case "equals":
if asFloat(val) != asFloat(cr.Value) {
return false
}
case "contains":
vs, _ := cr.Value.(string)
if !strings.Contains(strings.ToLower(fmt.Sprint(val)), strings.ToLower(vs)) {
return false
}
default:
return false
}
}
return true
}
func asFloat(v any) float64 {
switch n := v.(type) {
case float64:
return n
case int:
return float64(n)
case string:
f, _ := strconv.ParseFloat(n, 64)
return f
default:
return -1
}
}
// getItem serves GET /<itemtype>/<id> for seeded CI types.
func (s *Server) getItem(path string) (int, string) {
parts := strings.SplitN(strings.TrimPrefix(path, "/"), "/", 2)
itemtype := parts[0]
id, err := strconv.Atoi(parts[1])
if err != nil {
return http.StatusNotFound, `[{"ERROR_ITEM_NOT_FOUND":true}]`
}
obj, ok := s.items[itemtype][id]
if !ok {
return http.StatusNotFound, `[{"ERROR_ITEM_NOT_FOUND":true}]`
}
return jsonReply(obj)
}
// inputObject extracts the "input" member and reports whether it is a
// JSON object (Change family) — the array form is a distinct error.
func inputObject(body []byte) (json.RawMessage, bool) {
var probe struct {
Input json.RawMessage `json:"input"`
}
if err := json.Unmarshal(body, &probe); err != nil || len(probe.Input) == 0 {
return nil, false
}
trimmed := bytes.TrimSpace(probe.Input)
if len(trimmed) == 0 || trimmed[0] != '{' {
return nil, false
}
return trimmed, true
}
func trimPrefixInt(path, prefix string) int {
n, _ := strconv.Atoi(strings.TrimPrefix(path, prefix))
return n
}
func itemtypeOf(path string) string {
return strings.TrimPrefix(path, "/search/")
}
func jsonReply(v any) (int, string) {
b, err := json.Marshal(v)
if err != nil {
return http.StatusInternalServerError, `[{"ERROR_MARSHAL":true}]`
}
return http.StatusOK, string(b)
}
+287
View File
@@ -0,0 +1,287 @@
// Package mcp implements a minimal stdio JSON-RPC MCP (Model Context
// Protocol) server over the glpi library — stdlib only, no third-party
// modules. Transport is newline-delimited JSON on the reader/writer
// pair. Tools: change_create, change_list, change_transition,
// change_followup, ci_search, ci_show. An optional agent profile id
// (e.g. 5 = Hotliner) is applied on the first tool call.
package mcp
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"strconv"
"sync"
"git.knownelement.com/ukrrs/mopac-glpi-go/glpi"
)
// protocolVersionDefault answers initialize when the client does not
// name one.
const protocolVersionDefault = "2025-06-18"
// Server is the MCP server over one glpi.Client.
type Server struct {
client *glpi.Client
profile int
once sync.Once
profileErr error
}
// New builds a Server. profileID > 0 switches the session's active
// profile (agent mode) on first use.
func New(c *glpi.Client, profileID int) *Server {
return &Server{client: c, profile: profileID}
}
// Serve reads newline-delimited JSON-RPC requests until EOF, writing
// one response line per request that carries an id (notifications are
// acknowledged by silence).
func (s *Server) Serve(in io.Reader, out io.Writer) error {
sc := bufio.NewScanner(in)
sc.Buffer(make([]byte, 0, 64*1024), 4<<20)
for sc.Scan() {
line := bytes.TrimSpace(sc.Bytes())
if len(line) == 0 {
continue
}
if err := s.handle(line, out); err != nil {
return err
}
}
return sc.Err()
}
// request is one inbound JSON-RPC message.
type request struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id"`
Method string `json:"method"`
Params struct {
ProtocolVersion string `json:"protocolVersion"`
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
} `json:"params"`
}
// response is one outbound JSON-RPC message (result XOR error).
type response struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id"`
Result any `json:"result,omitempty"`
Error *rpcError `json:"error,omitempty"`
}
type rpcError struct {
Code int `json:"code"`
Message string `json:"message"`
}
func (s *Server) handle(line []byte, out io.Writer) error {
var req request
if err := json.Unmarshal(line, &req); err != nil || req.Method == "" {
return nil // cannot route a malformed line; never guess an id
}
if len(req.ID) == 0 || string(req.ID) == "null" {
return nil // notification: no response per JSON-RPC
}
resp := response{JSONRPC: "2.0", ID: req.ID}
switch req.Method {
case "initialize":
pv := req.Params.ProtocolVersion
if pv == "" {
pv = protocolVersionDefault
}
resp.Result = map[string]any{
"protocolVersion": pv,
"capabilities": map[string]any{"tools": map[string]any{}},
"serverInfo": map[string]any{"name": "mglpi-mcp", "version": "0.1.0"},
}
case "ping":
resp.Result = map[string]any{}
case "tools/list":
resp.Result = map[string]any{"tools": toolDefs()}
case "tools/call":
resp.Result = s.callTool(req.Params.Name, req.Params.Arguments)
default:
resp.Result = nil
resp.Error = &rpcError{Code: -32601, Message: fmt.Sprintf("method not found: %s", req.Method)}
}
return writeLine(out, resp)
}
// ensureProfile applies the agent profile once per server lifetime (an
// API op; it also warms the session).
func (s *Server) ensureProfile() error {
s.once.Do(func() {
if s.profile > 0 {
s.profileErr = s.client.ChangeActiveProfile(context.Background(), s.profile)
}
})
return s.profileErr
}
// callTool dispatches one tools/call. Tool failures are RESULTS with
// isError=true (protocol errors are the -32601 path only).
func (s *Server) callTool(name string, args json.RawMessage) map[string]any {
if err := s.ensureProfile(); err != nil {
return toolError(err)
}
var a map[string]any
if len(args) > 0 {
if err := json.Unmarshal(args, &a); err != nil {
return toolError(fmt.Errorf("arguments are not an object"))
}
}
ctx := context.Background()
var payload any
switch name {
case "change_create":
title, _ := a["title"].(string)
if title == "" {
return toolError(fmt.Errorf("change_create requires title"))
}
content, _ := a["content"].(string)
id, err := s.client.CreateChange(ctx, title, content, argInt(a, "urgency", 3), argInt(a, "impact", 3))
if err != nil {
return toolError(err)
}
payload = map[string]any{"change": map[string]any{"id": id}}
case "change_list":
rows, err := s.client.ListChanges(ctx, argInt(a, "status", 0))
if err != nil {
return toolError(err)
}
payload = map[string]any{"changes": rows}
case "change_transition":
id := argInt(a, "id", 0)
status, ok := glpi.StatusID(argString(a, "status"))
if !ok {
status = argInt(a, "status", 0)
}
if id == 0 || status == 0 {
return toolError(fmt.Errorf("change_transition requires id and status"))
}
if err := s.client.TransitionChange(ctx, id, status); err != nil {
return toolError(err)
}
payload = map[string]any{"transitioned": map[string]any{"id": id, "status": glpi.StatusName(status)}}
case "change_followup":
id := argInt(a, "id", 0)
content, _ := a["content"].(string)
if id == 0 || content == "" {
return toolError(fmt.Errorf("change_followup requires id and content"))
}
if err := s.client.AddFollowup(ctx, id, content); err != nil {
return toolError(err)
}
payload = map[string]any{"followup": map[string]any{"items_id": id}}
case "ci_search":
rows, err := s.client.SearchCI(ctx, argString(a, "itemtype"), argString(a, "term"))
if err != nil {
return toolError(err)
}
type result struct {
ID int `json:"id"`
Name string `json:"name"`
}
results := make([]result, 0, len(rows))
for _, r := range rows {
results = append(results, result{ID: r.ID, Name: r.Name})
}
payload = map[string]any{"results": results}
case "ci_show":
id := argInt(a, "id", 0)
obj, err := s.client.GetItem(ctx, argString(a, "itemtype"), id)
if err != nil {
return toolError(err)
}
payload = obj
default:
return toolError(fmt.Errorf("unknown tool: %s", name))
}
b, err := json.Marshal(payload)
if err != nil {
return toolError(fmt.Errorf("cannot encode tool result"))
}
return map[string]any{
"content": []map[string]any{{"type": "text", "text": string(b)}},
"isError": false,
}
}
func toolError(err error) map[string]any {
return map[string]any{
"content": []map[string]any{{"type": "text", "text": err.Error()}},
"isError": true,
}
}
func argString(a map[string]any, key string) string {
s, _ := a[key].(string)
return s
}
func argInt(a map[string]any, key string, def int) int {
switch v := a[key].(type) {
case float64:
return int(v)
case string:
if n, err := strconv.Atoi(v); err == nil {
return n
}
}
return def
}
// toolDefs is the advertised tool surface (stable order).
func toolDefs() []map[string]any {
schema := func(required ...string) map[string]any {
props := map[string]any{}
for _, p := range required {
props[p] = map[string]any{"type": "string"}
}
return map[string]any{
"type": "object",
"properties": props,
"required": required,
}
}
full := func(req []string, opt map[string]string) map[string]any {
props := map[string]any{}
for _, p := range req {
props[p] = map[string]any{"type": "string"}
}
for p, t := range opt {
props[p] = map[string]any{"type": t}
}
return map[string]any{
"type": "object",
"properties": props,
"required": req,
}
}
return []map[string]any{
{"name": "change_create", "description": "Create a GLPI change (urgency/impact 1-5, 3=medium)", "inputSchema": full([]string{"title"}, map[string]string{"content": "string", "urgency": "integer", "impact": "integer"})},
{"name": "change_list", "description": "List GLPI changes (optional status filter)", "inputSchema": schema()},
{"name": "change_transition", "description": "Move a change to a status (name or numeric id)", "inputSchema": schema("id", "status")},
{"name": "change_followup", "description": "Append a followup note to a change", "inputSchema": schema("id", "content")},
{"name": "ci_search", "description": "Search CIs of an itemtype by name substring", "inputSchema": schema("itemtype", "term")},
{"name": "ci_show", "description": "Fetch one CI raw by itemtype and id", "inputSchema": schema("itemtype", "id")},
}
}
// writeLine emits one compact JSON response line.
func writeLine(out io.Writer, v any) error {
b, err := json.Marshal(v)
if err != nil {
return err
}
_, err = out.Write(append(b, '\n'))
return err
}
+218
View File
@@ -0,0 +1,218 @@
package mcp
import (
"encoding/json"
"strings"
"testing"
"time"
"git.knownelement.com/ukrrs/mopac-glpi-go/glpi"
"git.knownelement.com/ukrrs/mopac-glpi-go/internal/fakeglpi"
)
const (
testApp = "fake-app-token-0123456789"
testUser = "fake-user-token-0123456789"
)
// serve feeds one batch of JSON-RPC lines through the server and
// returns the response lines.
func serve(t *testing.T, s *Server, lines ...string) []map[string]any {
t.Helper()
var out strings.Builder
if err := s.Serve(strings.NewReader(strings.Join(lines, "\n")+"\n"), &out); err != nil {
t.Fatalf("Serve: %v", err)
}
var msgs []map[string]any
for i, line := range strings.Split(strings.TrimRight(out.String(), "\n"), "\n") {
if line == "" {
continue
}
var m map[string]any
if err := json.Unmarshal([]byte(line), &m); err != nil {
t.Fatalf("response line %d not json: %v (%q)", i+1, err, line)
}
msgs = append(msgs, m)
}
return msgs
}
func newServer(t *testing.T) (*Server, *fakeglpi.Server) {
t.Helper()
srv := fakeglpi.New(testApp, testUser)
t.Cleanup(srv.Close)
c := glpi.New(glpi.Config{BaseURL: srv.URL, AppToken: testApp, UserToken: testUser, Timeout: 5 * time.Second})
return New(c, 0), srv
}
func rpc(id int, method string, params map[string]any) string {
b, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params})
return string(b)
}
func TestInitializeHandshake(t *testing.T) {
s, _ := newServer(t)
msgs := serve(t, s, rpc(1, "initialize", map[string]any{
"protocolVersion": "2025-06-18",
"capabilities": map[string]any{},
"clientInfo": map[string]any{"name": "test", "version": "0"},
}))
if len(msgs) != 1 {
t.Fatalf("responses = %d, want 1", len(msgs))
}
res, _ := msgs[0]["result"].(map[string]any)
if res == nil {
t.Fatalf("no result: %+v", msgs[0])
}
pv, _ := res["protocolVersion"].(string)
if pv == "" {
t.Errorf("initialize response missing protocol_version: %+v", res)
}
info, _ := res["serverInfo"].(map[string]any)
if info == nil || info["name"] != "mglpi-mcp" {
t.Errorf("serverInfo = %+v", info)
}
}
func TestNotificationProducesNoResponse(t *testing.T) {
s, _ := newServer(t)
// A notification (no id) must not yield a response line.
msgs := serve(t, s, `{"jsonrpc":"2.0","method":"notifications/initialized"}`)
if len(msgs) != 0 {
t.Fatalf("responses = %+v, want none", msgs)
}
}
func TestToolsList(t *testing.T) {
s, _ := newServer(t)
msgs := serve(t, s, rpc(2, "tools/list", map[string]any{}))
res, _ := msgs[0]["result"].(map[string]any)
tools, _ := res["tools"].([]any)
want := map[string]bool{
"change_create": false, "change_list": false, "change_transition": false,
"change_followup": false, "ci_search": false, "ci_show": false,
}
if len(tools) != len(want) {
t.Fatalf("tools = %+v, want %d", tools, len(want))
}
for _, tl := range tools {
tm, _ := tl.(map[string]any)
name, _ := tm["name"].(string)
if _, ok := want[name]; !ok {
t.Errorf("unexpected tool %q", name)
}
if tm["inputSchema"] == nil {
t.Errorf("tool %q missing inputSchema", name)
}
want[name] = true
}
}
func TestToolCallsRoundTrip(t *testing.T) {
s, srv := newServer(t)
web := srv.AddItem("Computer", map[string]any{"name": "web-01", "serial": "ABC123"})
// change_create
msgs := serve(t, s, rpc(3, "tools/call", map[string]any{
"name": "change_create",
"arguments": map[string]any{
"title": "Quota accounting", "content": "<p>body</p>", "urgency": 3, "impact": 4,
},
}))
var created struct {
Content []struct {
Text string `json:"text"`
} `json:"content"`
}
b, _ := json.Marshal(msgs[0]["result"])
if err := json.Unmarshal(b, &created); err != nil || len(created.Content) == 0 {
t.Fatalf("create result = %s err %v", b, err)
}
var payload struct {
Change struct {
ID int `json:"id"`
} `json:"change"`
}
if err := json.Unmarshal([]byte(created.Content[0].Text), &payload); err != nil || payload.Change.ID == 0 {
t.Fatalf("tool text = %q err %v", created.Content[0].Text, err)
}
stored, ok := srv.Change(payload.Change.ID)
if !ok || stored.Name != "Quota accounting" || stored.Impact != 4 {
t.Fatalf("stored = %+v", stored)
}
// change_list
msgs = serve(t, s, rpc(4, "tools/call", map[string]any{"name": "change_list", "arguments": map[string]any{}}))
if !strings.Contains(msgs[0]["result"].(map[string]any)["content"].([]any)[0].(map[string]any)["text"].(string), "Quota accounting") {
t.Errorf("change_list text missing created change")
}
// change_transition
msgs = serve(t, s, rpc(5, "tools/call", map[string]any{
"name": "change_transition",
"arguments": map[string]any{"id": payload.Change.ID, "status": "solved"},
}))
if got, _ := srv.Change(payload.Change.ID); got.Status != fakeglpi.StatusSolved {
t.Errorf("status after transition = %d", got.Status)
}
// change_followup
msgs = serve(t, s, rpc(6, "tools/call", map[string]any{
"name": "change_followup",
"arguments": map[string]any{"id": payload.Change.ID, "content": "REPORT delivered"},
}))
if fups := srv.Followups(payload.Change.ID); len(fups) != 1 || fups[0].Content != "REPORT delivered" {
t.Errorf("followups = %+v", srv.Followups(payload.Change.ID))
}
// ci_search
msgs = serve(t, s, rpc(7, "tools/call", map[string]any{
"name": "ci_search",
"arguments": map[string]any{"itemtype": "Computer", "term": "web"},
}))
text := msgs[0]["result"].(map[string]any)["content"].([]any)[0].(map[string]any)["text"].(string)
if !strings.Contains(text, "web-01") {
t.Errorf("ci_search text = %q", text)
}
// ci_show
msgs = serve(t, s, rpc(8, "tools/call", map[string]any{
"name": "ci_show",
"arguments": map[string]any{"itemtype": "Computer", "id": web},
}))
text = msgs[0]["result"].(map[string]any)["content"].([]any)[0].(map[string]any)["text"].(string)
if !strings.Contains(text, "ABC123") {
t.Errorf("ci_show text = %q", text)
}
}
func TestToolCallErrorsAreResults(t *testing.T) {
s, _ := newServer(t)
msgs := serve(t, s,
rpc(9, "tools/call", map[string]any{"name": "no_such_tool", "arguments": map[string]any{}}),
rpc(10, "tools/call", map[string]any{"name": "change_create", "arguments": map[string]any{}}),
)
for i, m := range msgs {
res, _ := m["result"].(map[string]any)
if res == nil || res["isError"] != true {
t.Fatalf("response %d = %+v, want isError result", i, m)
}
}
}
func TestUnknownMethodIsProtocolError(t *testing.T) {
s, _ := newServer(t)
msgs := serve(t, s, rpc(11, "resources/list", map[string]any{}))
errObj, _ := msgs[0]["error"].(map[string]any)
if errObj == nil || errObj["code"] != float64(-32601) {
t.Fatalf("error = %+v, want -32601", errObj)
}
}
func TestPing(t *testing.T) {
s, _ := newServer(t)
msgs := serve(t, s, rpc(12, "ping", map[string]any{}))
if msgs[0]["result"] == nil {
t.Fatalf("ping = %+v", msgs[0])
}
}
+28
View File
@@ -0,0 +1,28 @@
// Command fakeglpi boots the in-memory fake GLPI on a fixed address for
// the smoke run (see smoke/smoke.sh), with a few demo CIs seeded and an
// optional agent-profile gate. The real CMDB is never contacted.
package main
import (
"flag"
"log"
"os"
"git.knownelement.com/ukrrs/mopac-glpi-go/internal/fakeglpi"
)
func main() {
addr := flag.String("addr", ":8602", "listen address")
requireProfile := flag.Int("require-change-profile", 0, "reject change creation unless this profile is active (agent-mode gate)")
flag.Parse()
app := os.Getenv("FAKE_APP_TOKEN")
if app == "" {
app = "smoke-app-token-0123456789"
}
user := os.Getenv("FAKE_USER_TOKEN")
if user == "" {
user = "smoke-user-token-0123456789"
}
log.Printf("fakeglpi listening on %s", *addr)
log.Fatal(fakeglpi.ListenAndServe(*addr, app, user, *requireProfile))
}
Executable
+175
View File
@@ -0,0 +1,175 @@
#!/bin/sh
# End-to-end smoke for mglpi: builds the CLI + MCP server in the Docker
# builder, boots the FAKE GLPI in a container on 127.0.0.1:8602 (with
# the agent-profile gate on: change creation needs profile 5), drives
# the real binaries from the host through 0600 env files, and asserts
# the full command surface (whoami, change create/list/show/transition/
# followup, ci search/show, -o json, MCP handshake, exit codes) plus
# token redaction. No real CMDB is ever contacted. Only the exact
# container ID spawned here is removed.
set -e
cd "$(dirname "$0")/.."
IMAGE="golang@sha256:e8c859f5632dcfde7b32d2012b4351728f6437930887c2f6a91ea242459e5514"
PORT=8602
APP_TOK="smoke-app-token-0123456789"
USER_TOK="smoke-user-token-0123456789"
CID=""
cleanup() {
if [ -n "$CID" ]; then
docker rm -f "$CID" >/dev/null 2>&1 || true
fi
rm -rf .smoke
}
trap cleanup EXIT INT TERM
mkdir -p .smoke
umask 077
echo "--- build CLI + MCP (docker builder)"
docker run --rm -v "$PWD:/h" -w /h \
-u "$(id -u):$(id -g)" -e HOME=/tmp -e GOFLAGS=-buildvcs=false \
"$IMAGE" sh -c 'go build -o bin/mglpi ./cmd/mglpi && go build -o bin/mglpi-mcp ./cmd/mglpi-mcp'
echo "--- boot fake GLPI (container, port $PORT, agent gate: profile 5)"
CID=$(docker run -d --rm \
-v "$PWD:/h" -w /h \
-u "$(id -u):$(id -g)" -e HOME=/tmp -e GOFLAGS=-buildvcs=false \
-p 127.0.0.1:$PORT:8602 \
-e FAKE_APP_TOKEN="$APP_TOK" -e FAKE_USER_TOKEN="$USER_TOK" \
"$IMAGE" go run ./smoke/fakeglpi -addr :8602 -require-change-profile 5)
# wait for the fake to answer (any HTTP response, even 400, proves it is up)
i=0
until [ -n "$CID" ] && \
[ "$(docker inspect -f '{{.State.Running}}' "$CID" 2>/dev/null)" = "true" ] && \
curl -s -o /dev/null --max-time 2 "http://127.0.0.1:$PORT/"; do
i=$((i+1))
if [ "$i" -ge 60 ]; then
echo "smoke: fake GLPI did not come up; logs:" >&2
docker logs "$CID" >&2 || true
exit 1
fi
sleep 1
done
# plain.env has NO profile: the agent gate must reject it.
printf 'MGLPI_URL=http://127.0.0.1:%s/apirest.php\nMGLPI_APP_TOKEN=%s\nMGLPI_USER_TOKEN=%s\n' \
"$PORT" "$APP_TOK" "$USER_TOK" > .smoke/plain.env
# agent.env = agent mode: auto-switch to profile 5 (Hotliner) after init.
cp .smoke/plain.env .smoke/agent.env
printf 'MGLPI_PROFILE_ID=5\n' >> .smoke/agent.env
chmod 600 .smoke/plain.env .smoke/agent.env
mglpi_plain() { ./bin/mglpi --config .smoke/plain.env "$@"; }
mglpi_agent() { ./bin/mglpi --config .smoke/agent.env "$@"; }
echo "--- whoami (profiles)"
mglpi_plain whoami > .smoke/whoami.out
grep -q "Hotliner" .smoke/whoami.out
grep -q "Super-admin" .smoke/whoami.out
grep -q "\[active\]" .smoke/whoami.out
echo "--- agent gate: create WITHOUT profile is rejected (exit 2, http 403)"
if mglpi_plain change create --title "Smoke: gated" --content - > .smoke/gate.out 2> .smoke/gate.err </dev/null; then
echo "smoke: create without profile should fail" >&2; exit 1
fi
grep -q "http 403" .smoke/gate.err || { echo "smoke: gate stderr missing http 403: $(cat .smoke/gate.err)" >&2; exit 1; }
[ "$(wc -l < .smoke/gate.err)" -eq 1 ] || { echo "smoke: stderr not one line: $(cat .smoke/gate.err)" >&2; exit 1; }
[ ! -s .smoke/gate.out ] || { echo "smoke: stdout not empty on failure" >&2; exit 1; }
echo "--- change create (agent env auto-switch, stdin body, json out)"
mglpi_agent change create --title "Smoke: quota accounting" \
--urgency 3 --impact 4 --content - <<'EOF' > .smoke/create.out
## Scope
- smoke body
EOF
grep -q "created change #" .smoke/create.out
ID1=$(sed -n 's/^created change #\([0-9]*\)$/\1/p' .smoke/create.out)
[ -n "$ID1" ] || { echo "smoke: no id in create out: $(cat .smoke/create.out)" >&2; exit 1; }
mglpi_agent change create --title "Smoke: json shape" --content - -o json </dev/null > .smoke/create.json.out
grep -q '"id"' .smoke/create.json.out
ID2=$(jq -r '.change.id' .smoke/create.json.out)
[ -n "$ID2" ] && [ "$ID2" != "null" ] || { echo "smoke: no id in create json" >&2; exit 1; }
echo "--- change list + status filters (text and json)"
mglpi_agent change list > .smoke/list.out
grep -q "Smoke: quota accounting" .smoke/list.out
mglpi_agent change list --status new > .smoke/listn.out
grep -q "Smoke: quota accounting" .smoke/listn.out
mglpi_agent change list -o json > .smoke/list.json.out
jq -e '.changes | length == 2' .smoke/list.json.out >/dev/null
echo "--- change show + transition + followup"
mglpi_agent change show "$ID1" > .smoke/show.out || { echo "smoke: show failed: $(cat .smoke/show.out)" >&2; exit 1; }
grep -q "Smoke: quota accounting" .smoke/show.out || { echo "smoke: show missing title: $(cat .smoke/show.out)" >&2; exit 1; }
grep -q "smoke body" .smoke/show.out || { echo "smoke: show missing body: $(cat .smoke/show.out)" >&2; exit 1; }
mglpi_agent change transition "$ID2" solved > .smoke/trans.out 2> .smoke/trans.err || { echo "smoke: transition failed: $(cat .smoke/trans.err)" >&2; exit 1; }
grep -q "updated change #$ID2" .smoke/trans.out || { echo "smoke: transition confirmation wrong: $(cat .smoke/trans.out)" >&2; exit 1; }
mglpi_agent change followup "$ID2" --content - <<'EOF' > .smoke/fup.out 2> .smoke/fup.err
REPORT delivered: smoke followup
EOF
grep -q "added followup to change #$ID2" .smoke/fup.out || { echo "smoke: followup failed: $(cat .smoke/fup.err)" >&2; exit 1; }
echo "--- ci search + show"
mglpi_agent ci search Computer smoke > .smoke/ci.out
grep -q "smoke-web-01" .smoke/ci.out
mglpi_agent ci search Computer smoke -o json > .smoke/ci.json.out
CIID=$(jq -r '.results[0].id' .smoke/ci.json.out)
[ -n "$CIID" ] && [ "$CIID" != "null" ] || { echo "smoke: no CI in search json" >&2; exit 1; }
mglpi_agent ci show Computer "$CIID" -o json > .smoke/cishow.out
jq -e '.serial' .smoke/cishow.out >/dev/null
echo "--- failure path: missing change (exit 2, one-line stderr with http code)"
if mglpi_agent change show 999 > .smoke/missing.out 2> .smoke/missing.err; then
echo "smoke: missing change should fail" >&2; exit 1
fi
grep -q "http 404" .smoke/missing.err
[ "$(wc -l < .smoke/missing.err)" -eq 1 ] || { echo "smoke: stderr not one line" >&2; exit 1; }
[ ! -s .smoke/missing.out ] || { echo "smoke: stdout not empty on failure" >&2; exit 1; }
echo "--- failure path: wrong user token (exit 2, no token material in stderr)"
printf 'MGLPI_URL=http://127.0.0.1:%s/apirest.php\nMGLPI_APP_TOKEN=%s\nMGLPI_USER_TOKEN=wrong-user-token\n' \
"$PORT" "$APP_TOK" > .smoke/bad.env
chmod 600 .smoke/bad.env
if ./bin/mglpi --config .smoke/bad.env change list 2> .smoke/bad.err; then
echo "smoke: wrong user token should fail" >&2; exit 1
fi
grep -q "http 400" .smoke/bad.err
echo "--- failure path: loose env file (exit 1)"
cp .smoke/plain.env .smoke/loose.env
chmod 644 .smoke/loose.env
if ./bin/mglpi --config .smoke/loose.env change list 2> .smoke/loose.err; then
echo "smoke: loose env file should be refused" >&2; exit 1
fi
grep -q "insecure mode" .smoke/loose.err
echo "--- MCP handshake (initialize + tools/list + change_list over stdio)"
printf '%s\n' \
'{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"smoke","version":"0"}}}' \
'{"jsonrpc":"2.0","method":"notifications/initialized"}' \
'{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}' \
'{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"change_list","arguments":{}}}' \
| ./bin/mglpi-mcp --config .smoke/agent.env > .smoke/mcp.out 2> .smoke/mcp.err
# Three response lines: the notification is answered with silence.
[ "$(wc -l < .smoke/mcp.out)" -eq 3 ] || { echo "smoke: MCP responses = $(wc -l < .smoke/mcp.out), want 3" >&2; exit 1; }
sed -n 1p .smoke/mcp.out | jq -e '.result.protocolVersion' >/dev/null
sed -n 2p .smoke/mcp.out | jq -e '.result.tools | length == 6' >/dev/null
sed -n 3p .smoke/mcp.out | jq -e '.result.content[0].text | fromjson | .changes | length == 2' >/dev/null
echo "--- redaction: no token material in any captured output"
for f in .smoke/*.out .smoke/*.err; do
if grep -qF "$APP_TOK" "$f" || grep -qF "$USER_TOK" "$f"; then
echo "smoke: token leaked into $f" >&2
exit 1
fi
done
if grep -qF "wrong-user-token" .smoke/bad.err; then
echo "smoke: wrong token echoed" >&2; exit 1
fi
echo "smoke: OK"